javascript - 如何将相同的 Prop 传递给组件中的每个子组件

标签 javascript reactjs

我有一个正在渲染条件不同组件的组件。我不能在每个地方传递相同的 Prop ,因为这会破坏漂亮的代码。我该如何优化它?

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

  }
}

事实上,还有更多的 props(不仅仅是 x)会破坏代码。但它们总是一样的。

每个组件都有属性 x 和值 y。我不想将其传递给每个组件。

最佳答案

您可以使用组件映射并将 Prop 存储在变量中,如下所示:

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

关于javascript - 如何将相同的 Prop 传递给组件中的每个子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57803532/

相关文章:

javascript - ReactJS传递多个元素

javascript - 使用 Object.freeze() 扩展函数对象 - 无法添加字段

javascript - RSelenium:向下滚动以加载网页内容

javascript - 关于 JQuery 脚本

javascript - Webdriver 找不到 "new loaded element"的 xpath

reactjs - react 路由器属性值

javascript - 关于我在星球大战应用程序中遇到的问题

javascript - React 中花括号内的花括号

reactjs - 圆环图 : Trigger legend or pie click event while selecting outside filter state change

javascript - 尝试将 xml 节点值中的小数四舍五入为两位数