简体   繁体   中英

React's setState() not working for nested DOM elements

I added a button inside my react application ,which sets some state property. Code :

<button onClick={this.on} className = "add-button" >Add New City</button>

It works fine . The problem is , when I paste this code inside some nested DOM element, like

<div><tr><td>...JSX...</td></tr></div>

Its not updating the store.I have also checked like this:

this.setState({ focus: true },() => {alert(this.state.focus)});

But it's not working.How to solve this?

Here is the sample code. It seems to change the state according to your code structure.

Are you having a problem in toggling the state value from true to false or vice versa?

 class Test extends React.Component { constructor(props) { super(props); this.state = {focus: false}; this.on = this.on.bind(this); } on(){ console.log("Intial State Value" ,this.state); this.setState({focus : !this.state.focus},() => (console.log("Changed State Value",this.state))); } render() { return ( <div> <div> <tr> <td> <button onClick={this.on} className = "add-button" >Add New City</button> </td> </tr> </div> </div> ); } } ReactDOM.render(<Test/>, document.getElementById('app')) 
 <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='app' /> 

You have a click handler in the parent table element and child button . When you click the button the click event is going to be propagated to the parent and switch focus back to false.

You can change this behavior by using event.stopPropagation in the parent.

 class Legs extends React.Component { state = { focus: false ,index: null } constructor(props) { super(props); this.on = this.on.bind(this); this.off = this.off.bind(this); } on(event) { event.stopPropagation(); this.setState({ focus: true }, console.log("Focus")) } off() { this.setState({ focus: false }, console.log("Off") ); } render () { return ( <div> <table className="mdl-data-table mdl-js-data-table " onClick={this.off}> <thead > <tr > <th >City</th> <th>No. Of Nights</th> <th></th> <th></th> </tr> </thead> <tbody> { this.props.legs.map ( (leg,index) => { return ( <tr key ={index} > <td>{leg}</td> <td><button className="material-icons" onClick = {this.on}>mode_edit</button></td> </tr> ); }) } </tbody> </table> </div> ); } } ReactDOM.render(<Legs legs={['l1','l2']}/>, document.getElementById('root')); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script> <div id="root"></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