我已经尝试让它工作一段时间了,但我不确定我做错了什么。我的表单组件有包含常规 html 标记和输入的子组件。如果 child 是输入,我想添加 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
}
最佳答案
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 .
关于javascript - 从 React.Children 获取返回变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33702206/