0

我有一个对话框组件,页眉、页脚和正文作为props.children

我的代码看起来像。

<Dialog>
<p key='header'>Header</p>
<p key='body'>body</p>
<p key='footer'><Footer</p>
</Dialog>

在 Dialog.js 中

render() {
return(
<div className='modal'>
{this.props.children.find(obj => obj.key==='header')}
{this.props.children.find(obj => obj.key==='body')}
{this.props.children.find(obj => obj.key==='footer')}
</div>
)
}

这是通过名称(键)传递孩子的最佳方式吗?

我误用了“钥匙”吗?

4

2 回答 2

1

如果您想根据他们的道具将自定义道具传递给孩子:

render() {
   return(
      <div className='modal'>
         {React.Children.map(this.props.children, child => {
            switch (child.key) {
               case: 'header':
                  return React.cloneElement(child, {
                     className: 'customClass' 
                  });
           ... // do every case in switch
         })}
      </div>
    )
}

您可以这样做以将密钥传递给 className :

return (
      <div>
        {React.Children.map(this.props.children, child => {
          return React.cloneElement(child, {
            className: child.key
          });
        })}
      </div>
    );

如果可能的话,当您在代码中声明这些子代以获得更好的性能时,您应该直接处理:

<Dialog>
    <p key='header' className='dialog-header' >Header</p>
    <p key='body' className='dialog-body'>body</p>
    <p key='footer' className='dialog-footer'><Footer</p>
</Dialog>

简单地渲染它们{this.props.children}

于 2018-02-05T09:17:29.510 回答
1

Key应该是reserved keywordReact 中的一个。如果您希望使用元素中的 id,请将其传递为id而不是传递。key对于我来说,您试图为每个子键找到相关的子键对我来说似乎毫无用处。你会简单地写

render() {
   return(
      <div className='modal'>
         {this.props.children}
      </div>
    )
}
于 2018-02-05T08:14:04.763 回答