[英]ReactJS: Is there a better way of doing this?
Basically, on hover i am changing the text color of a link, I was able to achieve what i needed, however, this looks too much of code for me, I believe there should be a better way. 基本上,在悬停时,我正在更改链接的文本颜色,我能够实现所需的功能,但是,这对我来说似乎太多了代码,我相信应该有更好的方法。 I am wondering if there is a better logic than this. 我想知道是否有比这更好的逻辑。 Please suggest. 请提出建议。
class App extends React.Component {
constructor() {
super();
this.state = {
link_su: false,
link_si: false
};
}
componentDidMount() {
this.hover_signup = document.getElementById("signup");
this.hover_signin = document.getElementById("signin");
this.hover_signup.addEventListener("mouseenter", this.colorChange);
this.hover_signup.addEventListener("mouseleave", this._colorChange);
this.hover_signin.addEventListener("mouseenter", this.colorChange);
this.hover_signin.addEventListener("mouseleave", this._colorChange);
}
componentWillUnmount() {
//removing all event listeners.
}
colorChange = e => {
if (e.target.id == "signup") {
this.setState({ link_su: !this.state.link });
} else {
this.setState({ link_si: !this.state.link });
}
};
_colorChange = e => {
if (e.target.id == "signup") {
this.setState({ link_su: this.state.link });
} else {
this.setState({ link_si: this.state.link });
}
};
render() {
return (
<main role="main" className="inner cover">
<a
href="/signup"
className="btn btn-lg btn-secondary"
style={link_su ? { color: "white" } : { color: "#282c34" }}
id="signup"
>
Sign Up
</a>
<br />
<br />
<a
href="/signin"
className="btn btn-lg btn-secondary"
style={link_si ? { color: "white" } : { color: "#282c34" }}
id="signin"
>
Sign In
</a>
</main>
);
}
}
Yes there is an easier way, this can all be done with CSS using the :hover
selector. 是的,有一种更简单的方法,可以使用CSS通过:hover
选择器来完成。
For example: 例如:
a { color: blue; } a.link1:hover { color: red; } a.link2:hover { color: yellow; }
<a class="link1" href="">Link 1</a> <a class="link2" href="">Link 2</a>
Edit : 编辑 :
If you use the style property to apply styles, I believe nothing (except !important
properties) can override that style, so if you provide the initial color through style but the hover color in a stylesheet, then the hover color will be overridden by the initial style and not show up. 如果您使用style属性应用样式,我相信没有任何东西( !important
属性除外)可以覆盖该样式,因此,如果您通过样式提供了初始颜色,但是在样式表中提供了悬停颜色,则悬停颜色将被最初的风格并没有出现。 So it's best not to mix in-line and stylesheet styles. 因此,最好不要混合使用内联样式和样式表样式。
Here's an example of what happens: 这是发生的情况的示例:
a.link1:hover { color: red; } a.link2:hover { color: red !important; }
<a class="link1" style="color: blue;" href="">Always Blue</a> <a class="link2" style="color: blue;" href="">Using Important (but you shouldn't)</a>
Note: I'm really not recommending using the !important
flag here, instead I'm recommending removing the in-line styles. 注意:我实际上不建议在这里使用!important
标志,而是建议删除嵌入式样式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.