[英]Pass props to a component, React Router V4
I have an app with this components tree: 我有一个这个组件树的应用程序:
App
Header
Main
Searcher
List_of_albums
Album
So, the idea is that in the main page I have a searcher of albums and this displays a list of albums after the search. 所以,我的想法是在主页面上有一个专辑搜索者,这会在搜索后显示一个专辑列表。 To do this, I am reading a .json file in the component Main and then the props are passed to List_of_albums and Album. 为此,我正在组件Main中读取.json文件,然后将props传递给List_of_albums和Album。
Everything works fine up to this point. 到目前为止,一切正常。
Now I want to acces with a buttom to the info of each Album in a new route: /id_of_the_album. 现在我想以新的路线中的每个相册的信息进行访问:/ id_of_the_album。
This buttom is localized in the component Album like this: 这个buttom本地化在组件Album中,如下所示:
let albumLink = `/${this.props.id}`
<Link to={albumLink}></Link>
To do that, I tried this in the component App: 为此,我在组件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>
)
}
}
Where Profile is the new component to show the album details. 其中个人资料是显示相册详细信息的新组件。 In this new Component I would like to open the jsons of the individual albums with something like this: 在这个新的组件中,我想用这样的东西打开各个专辑的jsons:
import singlejson from '../data/""""herethe_id_of_the_album"""".json'
but How can I pass to the component profile the id_of_the_album?? 但是如何将组件配置文件传递给id_of_the_album?
Write it like this: 写这样:
<Route path='/:id_of_the_album' render={props => <Profile {...props} /> } />
Now inside Profile
component, it should be available by: 现在在Profile
组件中,它应该可以通过以下方式获得:
this.props.match.params.id_of_the_album
In react router, when you are routing from one component to another component, you will have an object match
which has many properties within it. 在react路由器中,当您从一个组件路由到另一个组件时,您将拥有一个对象match
,其中包含许多属性。 One among them is params
which helps us to identify if any parameter is passed to the child component via the route. 其中一个是params
,它帮助我们识别是否有任何参数通过路由传递给子组件。
In your case, you can just use match.params.id_of_the_album
in your child component 在您的情况下,您可以在子组件中使用match.params.id_of_the_album
This link gives more info on react router. 此链接提供有关反应路由器的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.