简体   繁体   English

React 中的 DOM 未正确更新动态设置组件

[英]DOM in React is not updated properly set component dynamically

In react seems like DOM is not updating Lets say on click of a checkbox lets say id is checkbox1 I want to add another checkbox lets say id Checkbox2 should be checked as well so在反应中似乎DOM没有更新让我们说点击一个复选框让我们说id是checkbox1我想添加另一个复选框让我们说id Checkbox2也应该被选中

Checkbox id="checkbox1" onClick={this.handleChange.bind(this)} 
handleChange(){
    document.getElementById(checkbox2).checked=true;
}

while debug I can see below line executed在调试时我可以看到下面的行执行

document.getElementById(checkbox2).checked=true;

But DOM is not updating, checked it is working with JavaScript some issue with react但是 DOM 没有更新,检查它是否与 JavaScript 一起工作,有一些反应问题

Follow the react core principles update DOM using state only.遵循 react 核心原则,仅使用状态更新 DOM。 It is mainly diffing concept to update virtual DOM.更新虚拟DOM主要是不同的概念。 Below code snippet will work.下面的代码片段将起作用。

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      checked1: false,
      checked2: false
    }

  }

  handleCheck = () => {
    this.setState({ checked2: !this.state.checked2 });
  }
  render() {
    return (
      <div>
        <input type="checkbox" id="chk1" onChange={this.handleCheck} checked={this.state.checked1} />
        <input type="checkbox" id="chk2" onChange={this.handleCheck} checked={this.state.checked2} />

      </div>
    );
  }
}
export default App;

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

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