在React中实现页面跳转并传递参数是一个常见的需求。通过使用React Router,我们可以轻松实现这一功能。下面,我将通过5个实用案例,带你一步步入门如何用React实现页面跳转传值。
案例一:基本路由跳转
首先,我们需要设置一个基本的React Router环境。以下是一个简单的例子:
import React from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
const Home = () => <h1>首页</h1>;
const About = ({ match }) => <h1>关于我们 - {match.params.id}</h1>;
const App = () => (
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/">首页</Link>
</li>
<li>
<Link to="/about/123">关于我们</Link>
</li>
</ul>
</nav>
<Route path="/" exact component={Home} />
<Route path="/about/:id" component={About} />
</div>
</Router>
);
export default App;
在这个例子中,我们通过Link组件实现了页面跳转,并通过Route组件接收参数。
案例二:动态路由参数
动态路由参数允许我们根据URL中的参数来渲染不同的组件。以下是一个例子:
const Profile = ({ match }) => (
<div>
<h1>用户资料</h1>
<p>用户ID: {match.params.id}</p>
</div>
);
const App = () => (
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/profile/123">用户123</Link>
</li>
</ul>
</nav>
<Route path="/profile/:id" component={Profile} />
</div>
</Router>
);
在这个例子中,我们通过:id来定义一个动态路由参数。
案例三:使用history对象传递参数
除了通过路由参数传递,我们还可以使用history对象来传递参数。以下是一个例子:
import React from 'react';
import { BrowserRouter as Router, Route, Link, useHistory } from 'react-router-dom';
const Home = () => {
const history = useHistory();
const goToAbout = () => {
history.push('/about', { userId: 123 });
};
return (
<div>
<h1>首页</h1>
<button onClick={goToAbout}>跳转到关于我们</button>
<Route path="/about" component={About} />
</div>
);
};
const About = ({ location }) => (
<h1>关于我们 - 用户ID: {location.state.userId}</h1>
);
const App = () => (
<Router>
<div>
<Route path="/" exact component={Home} />
</div>
</Router>
);
export default App;
在这个例子中,我们通过history.push方法传递了一个对象,其中包含了需要传递的参数。
案例四:使用URLSearchParams传递参数
URLSearchParams是一个用于解析URL查询字符串并与之交互的接口。以下是一个例子:
const Home = () => {
const history = useHistory();
const goToAbout = () => {
history.push('/about?userId=123');
};
return (
<div>
<h1>首页</h1>
<button onClick={goToAbout}>跳转到关于我们</button>
<Route path="/about" component={About} />
</div>
);
};
const About = ({ location }) => {
const params = new URLSearchParams(location.search);
const userId = params.get('userId');
return <h1>关于我们 - 用户ID: {userId}</h1>;
};
const App = () => (
<Router>
<div>
<Route path="/" exact component={Home} />
</div>
</Router>
);
export default App;
在这个例子中,我们通过URL查询字符串传递了参数。
案例五:嵌套路由传值
在实际应用中,我们可能会遇到嵌套路由的情况。以下是一个例子:
const Dashboard = () => (
<div>
<h1>仪表盘</h1>
<ul>
<li>
<Link to="/dashboard/users">用户列表</Link>
</li>
</ul>
<Route path="/dashboard/users" component={Users} />
</div>
);
const Users = ({ match }) => (
<div>
<h2>用户列表</h2>
<ul>
<li>
<Link to="/dashboard/users/123">用户123</Link>
</li>
</ul>
<Route path="/dashboard/users/:id" component={UserProfile} />
</div>
);
const UserProfile = ({ match }) => (
<h1>用户资料 - {match.params.id}</h1>
);
const App = () => (
<Router>
<div>
<Route path="/dashboard" component={Dashboard} />
</div>
</Router>
);
export default App;
在这个例子中,我们通过嵌套路由实现了页面跳转和参数传递。
通过以上5个案例,相信你已经对React页面跳转传值有了更深入的了解。在实际开发中,根据具体需求选择合适的方法来实现页面跳转和参数传递是非常重要的。
