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

时间:2019-09-05 10:34:00

标签: javascript reactjs

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

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。我不想将此传递给每个组件。

2 个答案:

答案 0 :(得分:2)

您可以将道具保存到var中,然后将其传播到组件上:

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

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

答案 1 :(得分:2)

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

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方法之外,因为它不会改变。