react-router 2.8.1 js 点击事件 跳转
时间: 2023-10-08 13:10:16 浏览: 51
要实现路由跳转,你需要先安装 react-router-dom 模块。
然后在你的组件中,可以使用 Link 组件来实现路由跳转。例如:
```jsx
import React from 'react';
import { Link } from 'react-router-dom';
function MyComponent() {
return (
<div>
<h1>Hello World!</h1>
<Link to="/other-page">Go to other page</Link>
</div>
);
}
```
在上面的代码中,当用户点击 "Go to other page" 链接时,会自动跳转到 "/other-page" 路由。你需要在你的路由配置中定义 "/other-page" 路由对应的组件。
如果你需要在 JS 中编程式地实现路由跳转,可以使用 history 对象。例如:
```jsx
import React from 'react';
import { useHistory } from 'react-router-dom';
function MyComponent() {
const history = useHistory();
function handleClick() {
history.push('/other-page');
}
return (
<div>
<h1>Hello World!</h1>
<button onClick={handleClick}>Go to other page</button>
</div>
);
}
```
在上面的代码中,当用户点击 "Go to other page" 按钮时,会调用 handleClick 函数,该函数会使用 history.push 方法来实现路由跳转。