ReactJS:访问子方法

ReactJS: access child method

我正在尝试为我正在进行的项目制作一个简单的表单系统,这个想法很简单。我有一个 FormStore 可以在其中注册表单,可以将组件注册到这些表单,并且可以检索所有数据。

我想让它尽可能自动化,所以当安装 <Form> 元素时,它应该搜索任何子元素以查找 isFormItem 属性,并自动注册该输入带有一些回调的字段以获取在输入元素中定义的值。

我面临的问题是我不知道如何从更高级别的组件访问子组件。我认为没有办法使用 refs,因为它们必须手动分配,而这正是我要避免的。

这是我 Form.react.jsx 中的相关片段。这是我尝试将每个输入字段附加到表单的地方。

  componentDidMount() {
    const name = this.props.name ||
      'form_' + Math.floor(Math.random() * 100000000);
    FormStore.registerForm(name);
    React.Children.forEach(this.props.children, (child) => {
      if (selectn('props.isFormItem', child)) {
        // I need to call child.attachToForm somehow...
      }
    });
  };

这些是Input.react.jsx的相关部分。

  constructor(props) {
    this.attachToForm = this.attachToForm.bind(this);
  }

  attachToForm(formName) {
    const name = this.props.name ||
      'formItem_' + Math.floor(Math.random() * 100000000);
    FormStore.attachToForm(formName, name, () => this.state.value);
  }

我试过像这样访问子组件的方法:

  React.Children.forEach(this.props.children, (child) => {
    if (selectn('props.isFormItem', child)) {
      child.type.prototype.attachToForm =
        child.type.prototype.attachToForm.bind(child);
      child.type.prototype.attachToForm(name);
    }
  });

但是调用原型并没有在任何地方绑定实际的对象实例,所以最终到处都有一大堆绑定,最后它除了乱七八糟之外根本不起作用.

有什么办法吗?我只是没有看到它...任何帮助将不胜感激。

您可以将 formName 作为道具传递给每个 Input 组件,然后将每个项目附加到它自己的 componentDidMount 方法中。

此外,getDefaultProps 方法对您来说似乎很方便。

类似于:

getDefaultProps() {
  return {
    name: 'form_' + Math.floor(Math.random() * 100000000)
  }
}
render() {
   return <Input formName={this.props.name} />
}

然后在输入组件中:

getDefaultProps() {
  return {
    name: 'formItem_' + Math.floor(Math.random() * 100000000)
  }
}
componentDidMount() {
  FormStore.attachToForm(this.props.formName, this.props.name, () => this.state.value)
}