简体   繁体   English

如何将相同的道具传递给Component中的每个孩子

[英]How pass the same props to every child in Component

I have a component which is rendering conditional different components. 我有一个呈现条件不同组件的组件。 I can't pass the same props in every place, because this destroy pretty code. 我不能在每个地方传递相同的道具,因为这会破坏漂亮的代码。 How can I optimize this? 我该如何优化呢?

render(){
  const {what, y} = this.props.ddd

  return(){
    {what === "XXX" && <> <SmthComp1 x=y /> <SmthComp2 x=y /> }
    {what === "ZZZ" && <> <SmthComp3 x=y /> <SmthComp34 x=y /> }
    {what === "YYY" && <> <SmthComp5 x=y /> <SmthComp12 x=y /> }
    {what === "BBB" && <> <SmthComp6 x=y /> <SmthComp23 x=y /> }
    {what === "GGG" && <> <SmthComp7 x=y /> <SmthComp21 x=y /> }

  }
}

In fact, there are more props (not only x), that breaks the code. 实际上,还有更多的道具(不仅是x),这破坏了代码。 But they are always the same. 但是它们总是一样的。

Every component has prop x with value y. 每个组件的prop x的值为y。 I don't want pass this to every component. 我不想将此传递给每个组件。

You can save props to a var and then spread them onto the component: 您可以将props保存到var中,然后将它们传播到组件上:

render(){
  const {what, y} = this.props.ddd
  const props = {x: y}

  return(){
    {what === "XXX" && <> <SmthComp1 {...props} /> <SmthComp2 {...props} /> }
    //...
  }
}

You can use a component map and store the props in a variable, like this: 您可以使用组件图并将道具存储在变量中,如下所示:

render() {
    const {what, y} = this.props.ddd

    const componentsMap = {
        "XXX" : [SmthComp1, SmthComp2],
        "ZZZ" : [SmthComp3, SmthComp34],
        "YYY" : [SmthComp5, SmthComp12],
        "BBB" : [SmthComp6, SmthComp23],
        "GGG" : [SmthComp7, SmthComp21],
    };

    const componentProps = { x: y };

    return() {
        <>
        {componentsMap[what].map(Component => <Component {...componentProps} />)}
        </>
    }
}

You can put componentsMap outside the render method because it will not change. 您可以将componentsMap放置在render方法之外,因为它不会改变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM