簡體   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