正如 cmets 对此答案所指出的那样,解决此问题的默认方法是使用带有 href 属性的锚元素(a 标记),该属性指向您要路由的目标 URL用户到。具有按钮外观但行为或锚点的按钮几乎是一种 Web 反模式。在这个答案中查看更多信息:https://stackoverflow.com/a/1667512/1460905。
也就是说,当网络应用程序需要执行某些操作然后才重定向用户时,肯定存在一种潜在的情况。在这种情况下,如果用户采取的主要操作是提交一些数据或真正执行操作,而重定向更多的是副作用,那么原始问题是有效的。
在这种情况下,为什么不使用window 对象的location 属性呢?它甚至提供了一个很好的功能方法来访问外部位置。请参阅ref。
所以,如果你有一个组件,说
class Button extends Component {
render() {
return (
<button onClick={this.handleClick.bind(this)} />
);
}
}
然后添加 handleClick 使组件看起来像
class Button extends Component {
handleClick() {
// do something meaningful, Promises, if/else, whatever, and then
window.location.assign('http://github.com');
}
render() {
return (
<button onClick={this.handleClick.bind(this)} />
);
}
}
无需导入window,因为它是全球性的。应该可以在任何现代浏览器中完美运行。
另外,如果你有一个声明为函数的组件,你可能会在状态改变时使用the effect hook 来改变位置,比如
const Button = () => {
const [clicked, setClicked] = useState(false);
useEffect(() => {
if (clicked) {
// do something meaningful, Promises, if/else, whatever, and then
window.location.assign('http://github.com');
}
});
return (
<button onClick={() => setClicked(true)}></button>
);
};