2015-11-13 60 views
1

我一直试图让这个工作一段时间,我不知道我做错了什么。我的表单组件的子项包含常规的html标记以及输入。如果孩子是一个输入,我想添加attachToForm和detachFromForm函数。如果它不是输入,我想继续遍历子元素以确保元素没有子输入字段。从React.Children获取返回变量

问题是无论我做什么,我都无法让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 
} 

回答

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

+0

嘿@JustinPowell感谢您的回应。我已经尝试过类似的问题,它只让孩子成为输入。所以当我渲染this.newChildren时,我没有标签或标题。我想通过使用第二个函数(traverseChildren),我可以跟踪当前的子节点,并将它添加到newChildren数组中,如果它没有和子节点输入的话? – ReganPerkins

+0

嘿@JustinPowell刚刚意识到你确实在标题中回答了问题,所以我会为我的问题的其他部分提出一个新问题。谢谢 – ReganPerkins