2017-03-22 3 views
0

特定のReactコンポーネントにpropを追加しようとしています。コンポーネントのすべての子ではありません。Reactに要素をクローンして特定の要素に小道具を追加するにはどうすればいいですか?

小道具は、次のコードのようになります。追加機能:

addProps (children) { 
const childProps = { doSomething: this.doSomething }; 

const recursiveAddProps = (children) => { 
    return React.Children.map(children, child => { 
    if (child.type !== GrandChild){ 
     if (child.props) recursiveAddProps(child.props.children); 
     return child; 
    } 
    return React.cloneElement(child, childProps); 
    }); 
} 
return recursiveAddProps(children); 
} 

Example

しかし、それは孫のコンポーネントへの関数のdoSomethingを追加されていないが、そう何のonClickイベントが解雇されていないコンポーネントをクリックします。

あなたは何をしますか?ご協力いただきありがとうございます!

答えて

1

あなたは中間の子供をクローニングし、recursiveAddPropsの戻り値を無視していません。 cloneElementはそうあなたが(未テスト)このようにそれを行う必要が変異していません:

const recursiveAddProps = (children) => { 
    return React.Children.map(children, child => { 
    if (child.type !== GrandChild) { 
     if (child.props) return React.cloneElement(child, { 
      children: recursiveAddProps(child.props.children), 
     }); 
     return child; 
    } 
    return React.cloneElement(child, childProps); 
    }); 
} 
関連する問題