react-router-dom V6版本
import { useNavigate } from 'react-router-dom';
function MyComponent() {
const navigate = useNavigate();
function handleClick() {
navigate('/new-path'); // 跳转到新路径,并在历史记录中创建新条目
}
return (
<button onClick={handleClick}>
Go to New Path
</button>
);
}
react-router-dom V5版本
import { useHistory } from 'react-router-dom';
function MyComponent() {
let history = useHistory();
function handleClick() {
history.push('/new-path'); // 跳转到新路径,并在历史记录中创建新条目
// 或者
history.replace('/new-path'); // 替换当前历史记录条目
}
return (
<button onClick={handleClick}>
Go to New Path
</button>
);
}
react-router-dom V4版本
import { withRouter } from 'react-router-dom';
function MyComponent({ history }) {
function handleClick() {
history.push('/new-path');
}
return (
<button onClick={handleClick}>
Go to New Path
</button>
);
}
export default withRouter(MyComponent);