2015-11-13 54 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