【问题标题】:Which are best option(s) to append many props to child component?哪些是将许多道具附加到子组件的最佳选择?
【发布时间】:2017-11-05 19:40:37
【问题描述】:

使用react 15.5.4

我有一个组件已经配置为在其子组件中跨 props。

export default class Component extends React.Component {

  render() {
    return (
      <TemplateAbout
        header={{
         title: 'WHY US',
         description: 'Our Team Member share the same Vision',
        }}
      />
    );
  }
}

我想将Component的接口改为NewComponent,如下例所示。

export default class NewComponent extends React.Component {

  render() {
    return (
      <TemplateAbout>
        <Header title="WHY US" description="Our Team Member share the same Vision" />
      </TemplateAbout>
    );
  }
}

最好的方法是什么?

【问题讨论】:

    标签: javascript reactjs ecmascript-6 jsx


    【解决方案1】:

    您可以使用对象扩展语法在 JSX 中传递道具。它将与其余的道具相结合。

     render() {
        const header = {
          title: 'WHY US',
          description: 'Our Team Member share the same Vision',
        }
        return (
          <TemplateAbout>
            <Header otherProps="otherValue" {...header} />
          </TemplateAbout>
        );
      }
    }
    

    【讨论】:

    • 我不明白你真正想要实现什么,如果你需要在语法上逐个传递各个道具,我认为没有简单的方法来做到这一点。跨度>
    • 我想说,在 TemplateAbout 的每个子项中使用 getChildContext 来自 TemplateAbout 和 contextType 可以做到这一点。每次getChildContext 更改返回不同的对象时,您可能必须重新渲染所有子对象。 (待确认,也许componentWillUpdate 有一个等价的上下文)。 @EvanSebastian 你是不是这么想的?
    • 如果所讨论的Header 是说明性的,并且&lt;TemplateAbout /&gt; 的子代作为道具计算/传递,那么是的,子上下文是一种将道具隐式传递为上下文的方法,尽管React.Children.map在这种情况下可能会更好。
    • 它与React.Children.map 配合得很好,但为什么不使用getChildContext,哪个性能最好?
    猜你喜欢
    • 2017-07-28
    • 2021-12-12
    • 2022-11-17
    • 1970-01-01
    • 2019-03-10
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多