gpt4 book ai didi

javascript - Reactjs sibling 类切换

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

我不想使用两个类

当按钮悬停时,如何使同级框显示为绿色?

目前所有框都悬停为绿色。

下面是带有片段的代码。

感谢您提前提供的帮助。

class Lol extends React.Component{
constructor(props){
super(props)
this.state = {
green : false
};
}
render = () =>{
let green = (this.state.green) ? 'green' : '';
let outs = [];
for(let i=0;i<5;i++){
outs.push(
<div>
<button onMouseOver={() => {
this.setState({green : true});
}}
onMouseLeave={() => {
this.setState({green : false});
}}
>
Turn box green
</button>
<div className={'box '+green}>
</div>
</div>
);
}
return (
<div>
{outs}
</div>
);
}
}
ReactDOM.render(<Lol />,document.getElementById("a"));
.box{
border:1px solid #000;
height:20px;
width:20px;
}
.green{
background:green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="a">
</div>

最佳答案

设置状态中悬停项目的索引,以及是否悬停某些内容。然后将存储的索引与当前迭代索引进行比较:

class Lol extends React.Component{
constructor(props){
super(props)
this.state = {
greenIndex: null
};
}
render = () =>{

let outs = [];
for(let i=0;i<5;i++){
const { greenIndex } = this.state;
const greenClass = (greenIndex === i) ? 'green' : '';

outs.push(
<div>
<button onMouseOver={() => {
this.setState({ greenIndex: i });
}}
onMouseLeave={() => {
this.setState({ greenIndex: null });
}}
>
Turn box green
</button>
<div className={'box '+greenClass}>
</div>
</div>
);
}
return (
<div>
{outs}
</div>
);
}
}
ReactDOM.render(<Lol />,document.getElementById("a"));
.box{
border:1px solid #000;
height:20px;
width:20px;
}
.green{
background:green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="a">
</div>

关于javascript - Reactjs sibling 类切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42914819/

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