简体   繁体   中英

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. But they are always the same.

Every component has prop x with value y. I don't want pass this to every component.

You can save props to a var and then spread them onto the component:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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