64

送信ボタンのあるフォームがあります。そのフォームは、何かの状態を false から true に設定する関数 onclick を呼び出します。次に、この状態を親に戻したいので、true の場合は componentA をレンダリングし、false の場合は componentB をレンダリングします。

どうすれば反応しますか?状態または小道具を使用する必要があることはわかっていますが、その方法がわかりません。また、これは一方向フロー反応の原則と矛盾していますか??

ComponentA コード:

<form onSubmit={this.handleClick}>


handleClick(event) {
    this.setState({ decisionPage: true });
    event.preventDefault();
  };

表示内容を制御する親コンポーネント:

return (
      <div>
      {this.props.decisionPage ?
        <div>
          <LoginPage />
        </div>
        :
        <div>
          <Decision showThanks={this.props.showThanks}/>
        </div>
      }
      </div>
    )
4

8 に答える 8

64

Move handleClick to the parent and pass it to the child component as a prop.

<LoginPage handleClick={this.handleClick.bind(this)}/>

Now in the child component:

<form onSubmit={this.props.handleClick}>

This way submitting the form will update the state in parent component directly. This assumes you don't need to access updated state value in child component. If you do, then you can pass the state value back from the parent to the child as a prop. One-way data flow is maintained.

<LoginPage  handleClick={this.handleClick.bind(this)} decisionPage={this.state.decisionPage}/>
于 2016-11-21T14:26:06.523 に答える
0

これはまさに私が望んでいたものです。しかし、子から親に更新される値として (customer_id, customer_name) を持つたとえば 50 レコードのデータ セットの場合、これは遅れます。子コンポーネントで React.useEffect を使用して setState を実行します

于 2022-01-07T09:41:14.607 に答える