简体   繁体   中英

Reactjs siblings class toggle

I dont want to use two classes

How can i make the sibling box appear green when button is hover ?

Currently all the boxes are hovered green.

Below is the code with the snippet.

Thanks for the help in advance.

 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> 

Set the index of the hovered item in state, as well as whether or not something is hovered. Then compare the stored index with the current iteration index:

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM