簡體   English   中英

當子組件作為屬性傳遞時,react狀態不會更新/傳遞給子組件

[英]react state is not updated/passed to child component when child component is passed as a property

我正在嘗試創建動態表單,因此我將一些jsx元素作為屬性傳遞給子組件。 即使狀態正在更新,更新后的狀態也不會傳遞給元素。 下面是代碼:

這是子組件,用於映射傳遞的控件並輸出它們。

class Form extends Component {
  render() {
    return (
      <div>
        {this.props.controls.map((c, i) => {
          return <React.Fragment key={i}>{c}</React.Fragment>;
        })}
      </div>
    );
  }
}

這是調用子組件的應用程序:

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      username: '',
      password: ''
    };

    this.controls = [
      <input
        type="text"
        onChange={this.onChangeUsername}
        value={this.state.username}
      />
    ];
  }

  componentDidUpdate() {
    console.log(this.state);
  }

  render() {
    return (
      <div className="App">
        <div className="app__group">
          <h1>This is not working</h1>
          <Form controls={this.controls} />
        </div>
        <div className="app__group">
          <h1>This is working</h1>
          <input
            type="text"
            onChange={this.onChangePassword}
            value={this.state.password}
          />
        </div>
      </div>
    );
  }

  onChangeUsername = e => {
    console.log('onChangeUsername', e.target.value);
    this.setState({ username: e.target.value });
  };

  onChangePassword = e => {
    console.log('onChangePassword');
    this.setState({ password: e.target.value });
  };
}

作為意外行為的示例,當輸入作為屬性傳遞給子組件時,我無法鍵入輸入。 狀態會更新,但不會傳遞給孩子,因此不會顯示文本。

另一方面,可以使用標准輸入元素,我可以鍵入並查看輸出。

我究竟做錯了什么?

問題是您試圖使某些東西“固定”為動態。 讓我們采用一種更實用的方法,它將刷新每個輸入,例如它們是動態的。

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      username: '',
      password: ''
    };
  }

  componentDidUpdate() {
    console.log(this.state);
  }

  render() {
    return (
      <div className="App">
        <div className="app__group">
          <h1>This is not working</h1>
          <Form controls={this.controls()} />
        </div>
      </div>
    );
  }

  controls = () => {
    return [<input
            type="text"
            onChange={this.onChangeUsername}
            value={this.state.username}
           />]
  }

  onChangeUsername = e => {
    console.log('onChangeUsername', e.target.value);
    this.setState({ username: e.target.value });
  };

  onChangePassword = e => {
    console.log('onChangePassword');
    this.setState({ password: e.target.value });
  };
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM