首页 > 解决方案 > React:在父组件中获取子组件组件的状态

问题描述

我有这个容器,并且没有放置在同一级别。当我单击按钮(放置在父级上)时,如何获取表单的状态?

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

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>
    );
  }
}

标签: reactjsreact-state-management

解决方案


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

首先,formRef在您的 App 类顶部添加:

formRef = React.createRef();

然后在 App 渲染中,将refprop 传递给您的 Form 标签:

<Form ref={this.formRef} />

最后,从子窗体中获取状态:

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

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

在这里结帐演示


推荐阅读