代码之家  ›  专栏  ›  技术社区  ›  George

反应js:为什么子组件更改父状态?

  •  0
  • George  · 技术社区  · 8 年前

    codepen example

    class NameForm extends React.Component {
      constructor(props) {
        super(props);
        this.state = {data: this.props.data};
      }
    
      handleChange(event) {
        let updatedData = Object.assign({}, this.state.data);
        updatedData[event.target.name][event.target.dataset.lang] = event.target.value;
    
        this.setState({
          data: updatedData
        });
      }
    
      render() {
        return (
          <form>
              {Object.keys(this.props.data.titles).map((l, index) => 
              <input type="text" name="titles" data-lang={l} value={this.state.data.titles[l]} onChange={this.handleChange.bind(this)} />
              )}
          </form>
        );
      }
    }
    
    class App extends React.Component {
      constructor(props) {
        super(props);
    
        this.state = {
          images: [{"titles": {"en": "deluxe1500x930.jpg"}
          }],
          count: 1
        };
      }
    
      render() {
        return (
            <div>
              {Object.keys(this.state.images).map((x,index) => 
                <div>
                  {this.state.images[x].titles.en}
                  <NameForm data={this.state.images[x]} />
                  <button onClick={(() => {this.setState({ count: 2 })}).bind(this)}>test</button>
                </div>
              )}
            </div>
        )
      }
    }
    
    1 回复  |  直到 8 年前
        1
  •  4
  •   omri_saadon    8 年前

    因为你用 this.props.data . 这个 这道具。数据 来自父母,因此当它改变时,状态也会改变。

    )通过使用扩展运算符而不是使用相同的引用。

    this.state = {data: ...this.props.data};