[英]Change the style of the react component based on its props
I have a Header.js
: 我有一个
Header.js
:
const Header = () => {
return (
<header className="header">
<Logo/>
<HeaderMenu target="home-link"/>
</header>);
}
and a HeaderMenu.js
: 和
HeaderMenu.js
:
class HeaderMenu extends React.Component {
render() {
return(
<nav className="header-menu">
<a id="home-link">Home</a>
<a id="project-link">Projects</a>
<a id="blog-link">Blog</a>
<a id="about-me-link">About Me</a>
</nav>
);
}
}
How can I change an a
elements style based on target
props? 我怎样才能改变
a
基于元素的风格target
的道具?
Example: if target="home-link"
, then an a
element with id="home-link"
has its text underlined and another a
element doesn't. 例如:如果
target="home-link"
,然后一个a
与元素id="home-link"
有其文字下划线,并且另一a
元素没有。
You can do this by applying a class to any element that you want to have styled differently. 您可以通过将一个类应用于您希望样式不同的任何元素来实现。 In your example of giving a different style to the link for the current page, you can iterate over your links and give an "active" class to the link whose id matches the target.
在为当前页面的链接赋予不同样式的示例中,您可以遍历链接,并为ID与目标匹配的链接赋予“活动”类。
For Example: 例如:
class HeaderMenu extends React.Component {
render() {
const { target } = this.props;
const linkData = [
{id: "home-link", title: "Home"},
{id: "project-link", title: "Projects"},
{id: "blog-link", title: "Blog"},
{id: "about-me-link", title: "About Me"},
];
const linkElements = linkNames.map(e => (
<a id={ e.id } className={ e.id === target ? "active" : "" }>{ e.title }</a>
));
return(
<nav className="header-menu">
{ linkElements }
</nav>
);
}
}
However if you use React Router (which you may want to do so the page doesn't refresh when a link is clicked) the <NavLink>
component takes an activeClassName
prop, which applies the given className any time the current location (url) matches the NavLink's to
prop (which is analogous to the a
tag's href
). 但是,如果您使用React Router (您可能希望这样做,则单击链接时页面不会刷新),
<NavLink>
组件采用activeClassName
,该activeClassName
将在当前位置(URL)匹配时应用给定的className。该NavLink的to
支撑(这是类似于a
标记的href
)。
variable
. variable
。 map
to add a
tag map
添加a
标签 className = 'active'
on the a
where target is matched. a
上设置className = 'active'
。 HeaderMenu.js
class HeaderMenu extends React.Component {
constructor(props) {
super(props);
this.menus = [
{ id: 'home-link', name: 'Home' },
{ id: 'project-link', name: 'Projests' },
// ...
];
}
render() {
return(
<nav className="header-menu">
{
this.menus.map(menu => (<a id={menu.id} className={this.props.target === menu.id ? 'active' : ''}>{menu.name}</a>))
}
</nav>
);
}
} }
css
: css
:
.active {
// text style when active
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.