如何将道具传递给路由器? [英] How to pass props to a router?

查看:38
本文介绍了如何将道具传递给路由器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件 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 传递到某个路由,你可以通过 Linkparams 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆