gpt4 book ai didi

javascript - 如何只改变一个元素 onHover (ReactJS)

转载 作者:行者123 更新时间:2023-12-01 01:19:58 25 4
gpt4 key购买 nike

所以我试图通过改变状态来改变悬停时的元素颜色,问题是所有元素都会因为状态而改变。如何做到只有一个元素会改变?

问题链接: https://repl.it/@RokasSimkus/TediousTestyOctagons

class App extends Component {
state={
hover:false
}
render() {
let onHover = () =>{
this.setState({hover:true})
};
let onOut = () =>{
this.setState({hover:false})
};
return (
<div className="App">
<a onMouseOver={onHover} onMouseOut={onOut} style={this.state.hover? {color:'red', fontSize:'50px', cursor:'pointer'}: {color:'blue', fontSize:'50px', cursor:'pointer'}}>CHANGE LANGUAGE</a>
<br/>
<a onMouseOver={onHover} onMouseOut={onOut} style={this.state.hover? {color:'orange', fontSize:'50px', cursor:'pointer'}: {color:'blue', fontSize:'50px', cursor:'pointer'}}>DO SOMETHING ELSE</a>
<br/>
<a onMouseOver={onHover} onMouseOut={onOut} style={this.state.hover? {color:'grey', fontSize:'50px', cursor:'pointer'}: {color:'blue', fontSize:'50px', cursor:'pointer'}}>AND ELSE</a>
</div>
);
}
}

最佳答案

您可以跟踪悬停元素的唯一标识符,然后在鼠标悬停时将 state.hover 设置为该标识符,并在鼠标移开时将其清除,而不是用 bool 值来跟踪悬停。

let onHover = (id) =>{
this.setState({hover: id})
};
let onOut = () =>{
this.setState({hover: null})
};

您只需将 anchor 更新为如下所示:

<a onMouseOver={() => onHover('CHANGE LANGUAGE'} onMouseOut={onOut} style={this.state.hover === 'CHANGE LANGUAGE' ? {color:'red', fontSize:'50px', cursor:'pointer'}: {color:'blue', fontSize:'50px', cursor:'pointer'}}>CHANGE LANGUAGE</a>

关于javascript - 如何只改变一个元素 onHover (ReactJS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54317448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com