我正在努力将悬停效果应用于父级 div 内的父级和所有子级。我正在尝试关注,但它不起作用..
function changeBackground(e) {
e.target.style.backgroundColor = "#ff6f00";
e.target.style.color = "#ffffff";
}
function resetBackground(e){
e.target.style.backgroundColor = "#ffffff";
e.target.style.color = "#616161";
}
class InfoBlogs extends React.Component{
render(){
return(
<div id = "parent" style = { styles.parentCard } onMouseOver={changeBackground}
onMouseLeave={resetBackground}>
<div style={ styles.child1Card } id = "head">
<div style = { styles.c11 }>
<h2 style={styles.cardTitle}>Challenge</h2>
</div>
<div style = { styles.c12 } id = "footer">
<IoIosLogIn style={ styles.iconStyle } />
</div>
</div>
<div style={ styles.child2Card }>
<p style={ styles.cardContent }> The sky is pink.</p>
</div>
</div>
);
}
}
当鼠标悬停在子元素上时,它会影响子元素的特定部分,而不是整个父元素。 谁能告诉我如何使用reactjs实现这一点
最佳答案
您的问题是e.target
,它并不总是绑定(bind)到该事件的元素。在这种情况下,您必须使用 currentTarget
,它始终是绑定(bind)到事件的元素,即使事件位于子元素上。
更改为:
function changeBackground(e) {
e.currentTarget.style.backgroundColor = "#ff6f00";
e.currentTarget.style.color = "#ffffff";
}
function resetBackground(e){
e.currentTarget.style.backgroundColor = "#ffffff";
e.currentTarget.style.color = "#616161";
}
我建议您将函数作为方法放入下面的类检查中:
class InfoBlogs extends React.Component{
constructor(props){
super(props);
this.changeBackground = this.changeBackground.bind(this);
this.resetBackground = this.resetBackground.bind(this);
}
changeBackground(e) {
e.currentTarget.style.backgroundColor = "#ff6f00";
e.currentTarget.style.color = "#ffffff";
}
resetBackground(e){
e.currentTarget.style.backgroundColor = "#ffffff";
e.currentTarget.style.color = "#616161";
}
render(){
return(
<div id="parent" style={ styles.parentCard }
onMouseOver={this.changeBackground}
onMouseLeave={this.resetBackground}>
...
</div>);
}
}
或者您可以使用 React.createRef()
以获得更好的用法:
class InfoBlogs extends React.Component{
constructor(props){
super(props);
this.parentRef = React.createRef();
this.changeBackground = this.changeBackground.bind(this);
this.resetBackground = this.resetBackground.bind(this);
}
changeBackground(e) {
this.parentRef.current.style.backgroundColor = "#ff6f00";
this.parentRef.current.style.color = "#ffffff";
}
resetBackground(e){
this.parentRef.current.style.backgroundColor = "#ffffff";
this.parentRef.current.style.color = "#616161";
}
render(){
return(
<div id="parent" ref={this.parentRef} style={ styles.parentCard }
onMouseOver={this.changeBackground}
onMouseLeave={this.resetBackground}>
...
</div>);
}
}
关于reactjs - react : apply hover to all elements inside parent div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60413220/