繁体   English   中英

React的setState()不适用于嵌套的DOM元素

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

我在我的react应用程序内添加了一个按钮,该按钮设置了一些state属性。 代码:

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

它工作正常。 问题是,当我将此代码粘贴到一些嵌套的DOM元素中时,例如

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

它没有更新商店。我也检查过这样的情况:

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

但这不起作用,如何解决呢?

这是示例代码。 似乎根据您的代码结构更改了状态。

在将状态值从true切换为false或反之亦然时遇到问题吗?

 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' /> 

table元素和子button都有一个单击处理程序。 当您单击按钮时, click事件将传播到父对象,并将焦点切换回false。

您可以通过在父级中使用event.stopPropagation来更改此行为。

 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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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