我不想使用两个类
当按钮悬停时,如何让兄弟框显示为绿色?
目前所有的盒子都是绿色的。
以下是代码段的代码。
感谢您的帮助。
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"));
&#13;
.box{
border:1px solid #000;
height:20px;
width:20px;
}
.green{
background:green;
}
&#13;
<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>
&#13;
答案 0 :(得分:2)
设置悬停项目的索引状态,以及是否悬停。然后将存储的索引与当前迭代索引进行比较:
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"));
&#13;
.box{
border:1px solid #000;
height:20px;
width:20px;
}
.green{
background:green;
}
&#13;
<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>
&#13;