繁体   English   中英

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

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

我有一个呈现条件不同组件的组件。 我不能在每个地方传递相同的道具,因为这会破坏漂亮的代码。 我该如何优化呢?

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 /> }

  }
}

实际上,还有更多的道具(不仅是x),这破坏了代码。 但是它们总是一样的。

每个组件的prop x的值为y。 我不想将此传递给每个组件。

您可以将props保存到var中,然后将它们传播到组件上:

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

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

您可以使用组件图并将道具存储在变量中,如下所示:

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} />)}
        </>
    }
}

您可以将componentsMap放置在render方法之外,因为它不会改变。

暂无
暂无

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

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