React で親の props を特定の子にだけ伝えたい
※ React 初心者ですのでその点ご留意ください。
props.children
<Parent> <Child /> <Child /> </Parent>
このように親子関係がある場合、 Parent
がその子である複数の Child
を描画するには、 props.children
を使用します。
const Parent = (props) => { return( <div> { props.children } </div> ) }
簡単ですね。
親の props を伝える
親の props
の値を props.children
に伝えるには、 React.Children.map
関数と React.cloneElement
関数を使用して、 props
を追加した Child
のコピーを使用するようにします。
<Parent foo={"bar"}> <Child /> <Child /> </Parent>
const Parent = (props) => { const children = React.Children.map(props.children, (child) => { return React.cloneElement(child, {foo: props.foo}) }) return( <div> { children } </div> ) } const Child = (props) => { return( <p>foo: {props.foo}</p> ) }
親の props を特定の子にだけ伝える
上の例では、 Parent
の子要素として Child
以外の要素があった場合、余計な props をその要素にも渡してしまうことになります。
<Parent foo={"bar"}> <Child /> <Child /> <SomeElement /> <Child /> </Parent>
この場合、 SomeElement
にも props.foo
が渡されてしまいます。
SomeElement
には渡さず、 Child
にだけ渡したいです。
React.Children.map
関数の第二引数に指定する関数の引数に渡される child
の type
属性を見ることによって、その子要素がどの要素であるかを判別することができました。
const Parent = (props) => { const children = React.Children.map(props.children, (child) => { if (child.type === Child) { return React.cloneElement(child, {foo: params.foo}) } else { return child } }) return( <div> { children } </div> ) } const Child = (props) => { return( <p>foo: {props.foo}</p> ) }