我一直试图让它工作一段时间,但我不确定我做错了什么。我的表单组件包含包含常规html标记和输入的子项。如果孩子是输入,我想添加attachToForm和detachFromForm函数。如果它不是输入,我想继续遍历子节点以确保元素没有子输入字段。
问题是无论我做什么,即使使用虚拟数据,我也无法让traverseChildren返回任何内容。我不确定我是否不理解基本的JS或React.children
registerInputs(children) {
React.Children.forEach(children, function(child) {
if (child.props && child.props.name) {
this.newChildren.push(React.cloneElement(child, {
detachFromForm: this.detachFromForm,
attachToForm: this.attachToForm,
key: child.props.name
}))
} else if (child.props && child.props.children){
var traverseChildren = this.traverseChildren(child.props.children, child);
//this.newChildren.push(traverseChildren);
console.log(traverseChildren) //=> undefined
}
}.bind(this));
console.log(this.newChildren) // =>[]
}
traverseChildren(children, current){
var current = current;
var me = React.Children.forEach(children, function(child) {
if (child.props && child.props.name) {
return React.cloneElement(child, {
detachFromForm: this.detachFromForm,
attachToForm: this.attachToForm,
key: child.props.name
});
} else if (child.props && child.props.children){
return "hello";//this.traverseChildren(child.props.children, current);
} else {
return current;
}
});
console.log(me) // => undefined
}
答案 0 :(得分:1)
React.Children.forEach不会返回值。它执行您为数组中的每个项目提供的函数。试试这个:
traverseChildren(children, current){
var current = current;
React.Children.forEach(children, function(child) {
if (child.props && child.props.name) {
return React.cloneElement(child, {
detachFromForm: this.detachFromForm,
attachToForm: this.attachToForm,
key: child.props.name
});
} else if (child.props && child.props.children){
this.traverseChildren(child.props.children, current);
} else {
console.log(current);
}
});
}
或者,也许您正在寻找React.Children.map。