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

时间:2018-04-03 03:49:16

标签: javascript reactjs

我在我的react应用程序中添加了一个按钮,它设置了一些状态属性。代码:

<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)});

但它没有用。如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

以下是示例代码。它似乎根据你的代码结构改变了状态。

您是否在将状态值从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' />

答案 1 :(得分:0)

您在父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>