[英]react-router v4's Route doesn't pass it's props to component - in React Typescript
[英]Pass props to a component, React Router V4
我有一个这个组件树的应用程序:
App
Header
Main
Searcher
List_of_albums
Album
所以,我的想法是在主页面上有一个专辑搜索者,这会在搜索后显示一个专辑列表。 为此,我正在组件Main中读取.json文件,然后将props传递给List_of_albums和Album。
到目前为止,一切正常。
现在我想以新的路线中的每个相册的信息进行访问:/ id_of_the_album。
这个buttom本地化在组件Album中,如下所示:
let albumLink = `/${this.props.id}`
<Link to={albumLink}></Link>
为此,我在组件App中尝试了这个:
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
class App extends Component {
constructor(){
super()
}
render () {
return (
<Router>
<Fragment>
<Header />
<Switch>
<Route exact path='/' render={() => {
return(
<Main />
)
}} />
<Route path='/:id_of_the_album' render={() => {
return(
<Profile />
)
}} />
</Switch>
</Fragment>
</Router>
)
}
}
其中个人资料是显示相册详细信息的新组件。 在这个新的组件中,我想用这样的东西打开各个专辑的jsons:
import singlejson from '../data/""""herethe_id_of_the_album"""".json'
但是如何将组件配置文件传递给id_of_the_album?
写这样:
<Route path='/:id_of_the_album' render={props => <Profile {...props} /> } />
现在在Profile
组件中,它应该可以通过以下方式获得:
this.props.match.params.id_of_the_album
在react路由器中,当您从一个组件路由到另一个组件时,您将拥有一个对象match
,其中包含许多属性。 其中一个是params
,它帮助我们识别是否有任何参数通过路由传递给子组件。
在您的情况下,您可以在子组件中使用match.params.id_of_the_album
此链接提供有关反应路由器的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.