我试图做一个项目我工作的一个简单的表格系统,而且想法很简单。我有一个FormStore
表单可以注册,组件可以注册到这些表单,并可以检索所有的数据。ReactJS:访问孩子的方法
我想使这个尽可能地自动化,所以当<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);
}
});
但调用的原型不实际的对象实例绑定的任何地方,这样在有一大堆绑定结束了无处不在,最终它除了四处乱糟糟外,没有任何工作。
是否有这样做的一些方法?我只是没有看到它...任何帮助,将不胜感激。
是的,好像我会采取不同的方法毕竟。我想过这样做,但这仍然会让额外的工作不得不为每个输入编写formName prop。我想我会用克隆的元素替换输入元素,并在那里执行任何附加操作。似乎没有什么麻烦。 – Pavlin
我更喜欢添加道具的详细方式,或者只是将它们添加到“地图”循环中。代码将更加清晰和容易维护。 – David