React:获取父组件中子组件的状态

React: Get state of children component component in parent

我有这个容器在哪里和不在同一层。单击按钮(放置在父按钮上)时如何获取表单状态?

我创建了一个演示来解决我的问题。

https://codesandbox.io/s/kmqw47p8x7

class App extends React.Component {
  constructor(props) {
    super(props);
  }

  save = () => {
    alert("how to get state of Form?");
    //fire api call
  };
  render() {
    return (
      <div>
        <Form />
        <button onClick={this.save}>save</button>
      </div>
    );
  }
}

理想情况下,您的表单提交操作属于 Form 组件 您可以将 button 放入 From 组件中,并将提交回调传递给表单。

  class App extends React.Component {
  constructor(props) {
    super(props);
  }

   save = (data) => {
     // data is passed by Form component
    alert("how to get state of Form?");
    //fire api call
  };
  render() {
    return (
      <div>
        <Form onFormSubmit={this.save} />
      </div>
    );
  }
}

要从父实例访问子实例,您需要了解 ref:

首先,在您的应用顶部添加 formRef class:

formRef = React.createRef();

然后在 App render 中,将 ref 属性传递给您的表单标签:

<Form ref={this.formRef} />

最后,从子表单获取状态:

save = () => {
    alert("how to get state of Form?");

    const form = this.formRef.current;
    console.log(form.state)
};

结帐演示 here

你可以这样写代码

https://codesandbox.io/s/23o469kyx0

如前所述,ref 可用于获取有状态组件实例并访问状态,但这会破坏封装:

<Form ref={this.formRef}/>

更好的方法是重构 Form 来处理这种情况,即接受 onChange 表单状态更改时触发的回调属性:

<Form onChange={this.onFormChange}/>

One thing I don't want to do is sync the state for onChange event, because within Form there might be another Form.

表单需要以任何方式处理;使用来自 grandparent 的引用是不可能达到嵌套形式的。 lifting the state up.

可能就是这种情况

例如在 parent 组件中:

  state = {
    formState: {}
  };

  onFormChange = (formState) => {
    this.setState(state => ({
      formState: { ...state.formState, ...formState }
    }));
  }

  render() {
    return (
      <Form state={this.state.formState} onChange={this.onFormChange} />
    );
  }

在表单组件中:

  handleChange = e =>
    this.props.onChange({
      [e.target.name]: e.target.value
    });

  render() {
    return (
        <input
          onChange={this.handleChange}
          name="firstName"
          value={this.props.state.firstName}
        />
    );
  }

这里是demo.