繁体   English   中英

如何为具有不同价值道具的不同路线呈现相同的反应成分?

[英]How to render same react component for different routes with different value props?

我想问问是否可以为不同的路线渲染相同的反应组件,但具有不同的价值道具:

我有这样的事情:

   <Switch>
      <Route
         exact
         path="/something1"
         render={props => (
            <SomeComponent
             {...props}
             buttonStyle="#65BDE0"
          />
       )}
    />
    <Route
       exact
       path="/something2"
       render={props => (
          <SomeComponent
           {...props}
           buttonStyle="#FFFFFF"
          />
       )}
    />
     <Route
       exact
       path="/something3"
       render={props => (
          <SomeComponent
           {...props}
           buttonStyle="#000000"
          />
       )}
    />
    </Switch>

如您所见,我有三个具有相同组件的不同路线,但是每种路线的buttonStyle都不同。 有没有一种方法可以简化此过程或更好的方法来处理此问题? 例如带有一个Route组件? 谢谢。

我怀疑您是否可以使用一个<Route />组件来执行此操作,因为Route只能具有一条路径。

但是,您可以通过创建路由数组来使其更加整洁。

它可能看起来像这样:

const routesWithProps = [
  {
    path: '/something1',
    props: {
      buttonStyle: '#65BDE0'
    }
  },
  {
    path: '/something2',
    props: {
      buttonStyle: '#FFFFFF'
    }
  },
  {
    path: '/something3',
    props: {
      buttonStyle: '#000000'
    }
  },
];

<Switch>
  {
    routesWithProps.map(route => (
      <Route
         exact
         path={route.path}
         key={route.path}
         render={props => <SomeComponent {...props} {...route.props} />} 
      />
    ))
  }
</Switch>

那将取决于您想要保留逻辑的位置。 如果您想简化路线,则可以使用带有something/:btn的单个路线组件,然后在<SomeComponent />具有按钮呈现逻辑。 您可以让/:btn是您希望按钮放入的彩色哈希,或者是某些只有您的应用才能解密的ID号。

一个例子是

export const SomeComponent = ({history}) => {
  const param = history.params.btn;
  if(param === 1) {
    return <div>Here i can add specific things </div>
  }
  // and so on

}

这不是因为它是最佳解决方案,而是这种想法可能会启动如何做的开始。 祝好运

暂无
暂无

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

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