ReactJS:访问子方法

时间:2015-09-07 11:25:19

标签: javascript forms reactjs reactjs-flux

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

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

我面临的问题是,我不知道如何从更高级别的组件访问子组件。我不认为有一种方法可以使用参考,因为那些必须手动分配,而这正是我试图避免的。

这是我的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);
    }
  });

但是调用原型并没有将实际的对象实例绑定到任何地方,所以最终到处都有一大堆绑定,最后除了非常凌乱之外它还没有进行任何工作。到处都是。

有没有办法做到这一点?我只是没有看到它...任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

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

此外,getDefaultProps方法似乎很方便。

类似的东西:

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

然后在Input组件中:

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