如何将道具传递给路由器? [英] How to pass props to a router?
问题描述
我有一个文件 route.js
从 'react' 导入 React从'react-dom'导入{渲染}从react-router-dom"导入 {HashRouter ,Route,Link}const 路由器 = (道具) =>(<HashRouter><div><路由精确路径="/" render={() =><list data={props.data}/>}/><Route path="/list" render={() =><表数据={props.data}/>}/>
</HashRouter>
这里是编辑页面代码-
import React, { Component} from 'react'导出默认类 Edit extends Component {使成为() {返回 (<div><center>{this.props.data}</center>
);}}
我想将列表数据传递到下一页.如何将道具从路由器传递到页面
如果你想将任何 props 传递到某个路由,你可以通过 Link
的 params
prop 传递它代码>.
在您的情况下,您可以在 FreindList 页面上的任何位置设置一个按钮,如下所示:
<按钮>编辑</按钮></链接>
您还可以在编辑页面中访问此数组.
不要忘记从反应路由器导入链接
由于您使用的是反应路由器 4 的 react-router-dom
,因此您可以使用以下内容:
您将在编辑组件的 this.props.location.state
中获得它.
有关 react router 4 的更多文档,请查看this>
I have a file route.js which has
import React from 'react'
import { render } from 'react-dom'
import {HashRouter ,Route,Link} from 'react-router-dom'
const Router = (props) => (
<HashRouter>
<div>
<Route exact path="/" render={() => <list data={props.data}/>}/>
<Route path="/list" render={() => <Table data={props.data}/>}/>
</div>
</HashRouter>
here is the edit page code-
import React, { Component} from 'react'
export default class Edit extends Component {
render() {
return (
<div>
<center>{this.props.data}</center>
</div>
);
}
}
i want to pass the list data to the next page.how can i pass props to page from router
If you want to pass any props to some route you can just pass it through the params
prop of Link
.
Here in your case you could just set a button anywhere on the FreindList page which should be like:
<Link to='edit' params={{data: props.data.name}}>
<button>Edit</button>
</Link>
Further you can access this array in the edit page aswel.
don not forget to import Link from react router
Since you are using react-router-dom
which is react router 4, you can just use, something like this:
<Link to={{
pathname: '/edit',
state: { data: props.data.name }
}}>
<button>Edit</button>
</Link>
You will get it in this.props.location.state
in the edit component.
For more documentation on react router 4 check this out
这篇关于如何将道具传递给路由器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!