React是怎么实现路由传参的?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
一、动态路由
跳转方法
Link
<Link to={{ pathname: "/user/add/1" }}>跳转新增页面</Link>
history.push
this.props.history.push("/user/add/1");
获参方法
this.props.match.params
二、路由query显示参数
Link跳转
<Link to={{ pathname: "/user/add", query: { id: 1 } }}> 跳转新增页面 </Link>
history.push
this.props.history.push({ pathname: "/user/add", //参数 query: { id: 1 }, });
获参方法
this.props.location.query
三、路由state隐式参数
Link跳转
<Link to={{ pathname: "/user/add", state: { id: 1 } }}> 跳转新增页面 </Link>
history.push
this.props.history.push({ pathname: "/user/add", state: { id: 1 }, });
获参方法
this.props.location.state
代码DEMO
入口App组件
class App extends React.Component { render() { return ( <BrowserRouter> <Route path="/user" exact component={User} /> //动态路由 <Route path="/user/add/:id?" component={UserAdd} /> {/* <Redirect to="/user" /> */} </BrowserRouter> ); } }
动态路由Demo
User组件
import React, { Component } from "react"; import { Link } from "react-router-dom"; export default class User extends Component { render() { return ( <div> <div className="user">User</div> {/* <Link to={{ pathname: "/user/add/1" }}>跳转新增页面</Link> */} <button onClick={() => { // 1. // this.props.history.push("/user/add/1"); // 2. this.props.history.push({ pathname: "/user/add/1", }); }} > 跳转新增页面 </button> </div> ); } }
UserAdd组件
import React, { Component } from "react"; export default class UserAdd extends Component { render() { console.log("this.props.match.params:", this.props.match.params); return <div>UserAdd</div>; } }
路由query显示参数Demo
User组件
import React, { Component } from "react"; import { Link } from "react-router-dom"; export default class User extends Component { render() { return ( <div> <div className="user">User</div> <Link to={{ pathname: "/user/add", query: { id: 1 } }}> 跳转新增页面 </Link> <button onClick={() => { this.props.history.push({ pathname: "/user/add", query: { id: 1 }, }); }} > 跳转新增页面 </button> </div> ); } }
路由state隐式参数Demo
User组件
import React, { Component } from "react"; import { Link } from "react-router-dom"; export default class User extends Component { render() { return ( <div> <div className="user">User</div> <Link to={{ pathname: "/user/add", state: { id: 1 } }}> 跳转新增页面 </Link> <button onClick={() => { this.props.history.push({ pathname: "/user/add", state: { id: 1 }, }); }} > 跳转新增页面 </button> </div> ); } }
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。