我为我网站的导航栏创建了一个自定义按钮组件。当用户单击按钮时,该组件返回一个重定向,将用户带到他们选择的页面。
export default class Button extends Component {
constructor(props){
super(props);
this.state = {redirect:false};
this._handleClick = this._handleClick.bind(this);
}
_handleClick(e) {
e.stopPropagation();
this.setState({redirect: true});
}
componentDidUpdate() {
if (this.state.redirect){
this.setState({redirect:false});
this.props.onRedirect();
}
}
render() {
if (this.state.redirect){
return <Redirect push to={this.props.dest}/>;
}
else {
return (
<li className="button" onClick={this._handleClick}>
<h5>{this.props.text}</h5>
</li>
);
}
}
}
现在,我想添加对应于同一页面不同部分的按钮。我知道的最简单的方法是使用散列链接。按钮将重定向到的地址的一个示例是:
/home#description
但是,React Router 不支持开箱即用。我查看了许多添加此功能的软件包,例如 react-router-hash-link和 react-scrollchor .然而,这些都不适用于重定向,而是依赖于 Link
或自定义组件。
如何将此功能添加到按钮?
最佳答案
您可以更新 window.location.href
,因为它不会触发页面刷新。
例如
window.location.href = '#your-anchor-tag';
关于javascript - React Router 重定向哈希链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45864594/