通过路线传递道具

时间:2018-05-22 14:22:35

标签: reactjs react-router

在反应中如何配置路由以传递道具。例如我的route.tsx是:

[1]["2018-05"]="15"

当引发/计数器时,如何将一些数据作为道具传递给我的export const routes = () => ( <Layout> <Route exact path='/' component={ Home } /> <Route path='/counter' component={ Counter } /> <Route path='/fetchdata' component={ FetchData } /> </Layout> ); 组件

4 个答案:

答案 0 :(得分:5)

这将完成工作:Render

    <Route
      path='/dashboard'
      render={(props) => <Dashboard {...props} isAuthed={true} />}
    />

希望这有帮助!

答案 1 :(得分:4)

您可以使用render道具。

  <Route 
     path='/counter' 
     render={(props) => (
       <Counter {...props} count={5} />
     )} 
  />

答案 2 :(得分:1)

如其他答案所述,这由render prop处理,给出了示例:

<Route path="/home" render={() => <div>Home</div>}/>

但是,我(和许多其他人)发现此语法非常难看。在Route传递的original issue道具上,有一个well-liked包装器,我想浮出水面,我做了一些改进,并提出了这种简洁有效的包装器:

const PropsRoute = ({component, path, ...otherProps}) => (
  <Route {...otherProps} path={path} render={routeProps => 
      React.createElement(component, {...otherProps, ...routeProps})
    } />
)     

可以按预期使用:

<Router>
   <main>
     <PropsRoute exact path="/" component={Home} auth={this.state.auth} />
   </main>
</router>

请注意,执行此操作会将Route道具向下传递到组件。传递给Route的 Any 道具不是“组件”或“路径”,将向下传递到该组件。在此公式中,任何routeProps(由react-router传递)将覆盖通过此语法传递的自定义props。

然后可以很容易地将其扩展为通用的登录模式:

const AuthedRoute = ({auth, ...props}) =>
  !auth.valid()? <Redirect to="/login" />: <PropsRoute {...{...props, auth: auth}} />;

编辑:截至2019年,我基本上已经放弃了这种方法,而赞成这样的事情:

<Route {...{
    path: "/path/to/component",
    render: ({ location }) => <MyComponent {...{
        location
    }}/>
}}/>

这看起来有些粗糙,但是它使嵌套在深处的渲染树更加清晰,并允许您在JSX参数中使用完整的Javascript。

答案 3 :(得分:0)

为简化操作,您可以围绕<Route>创建一个包装器:

const RouteWrapper = ({ children, ...props }) => {
    const childrenWithProps = props => React.Children.map(children, child => React.cloneElement(child, { ...props }))}
    return <Route {...props} render={childrenWithProps} />
}

用法:

<RouteWrapper
    exact
    path="/">
    <Component myProp={38} />
</RouteWrapper>
相关问题