将道具传递给React Router 4中的组件 [英] Passing props to component in React Router 4
问题描述
我是react-router的新手,我刚开始使用react-router V4编写应用程序。我想将道具传递给由< Match />
呈现的组件,我想知道什么是'最佳'或'正确'的方式。
I am new to react-router and I just started writing an app using react-router V4. I would like to to pass props to components rendered by <Match />
and I am wondering about what's the 'best' or 'proper' way to do so.
是通过这样做吗?
<Match pattern="/" render={
(defaultProps) => <MyComponent myProp = {myProp} {...defaultProps} />
}/>
这是(将道具传递给组件,由<匹配/ >
)即使是使用react-router这样做的好习惯,还是反模式或其他东西;如果是这样,为什么?
Is this (passing props to components to be rendered by <Match />
) even a good practice to do so with react-router or is it an antipattern or something; and if so, why?
推荐答案
你必须使用 render
prop而不是组件
传递自定义道具,否则只有默认路线道具( {match,location,history}
)。
You must use the render
prop instead of component
to pass on custom props, otherwise only default Route props are passed ({match, location, history}
).
我将我的道具传递给路由器和子组件,就像这样。
I pass my props to the Router and child components like so.
class App extends Component {
render() {
const {another} = this.props
return <Routes myVariable={2} myBool another={another}/>
}
}
const Routes = (props) =>
<Switch>
<Route path="/public" render={ (routeProps) =>
<Public routeProps={routeProps} {...props}/>
}/>
<Route path="/login" component={Login}/>
<PrivateRoute path="/" render={ (routeProps) =>
...
}/>
</Switch>
这篇关于将道具传递给React Router 4中的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!