React Router重定向哈希链接

sty*_*ybl 7 javascript reactjs react-router

我为我网站的导航栏创建了一个自定义按钮组件.当用户单击某个按钮时,该组件将返回一个Redirect,该用户将用户带到他们选择的页面.

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>
            );
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,我想添加对应于同一页面不同部分的按钮.我所知道的最简单的方法是使用哈希链接.按钮将重定向到的地址的一个示例是:

/home#description
Run Code Online (Sandbox Code Playgroud)

但是,React Router不支持开箱即用.我查看了许多添加此功能的软件包,例如react-router-hash-linkreact-scrollchor.然而,这些都不适用于重定向,而是依赖于Link或依赖于自定义组件.

如何将此功能添加到按钮?

pur*_*eth 2

您可以更新,window.location.href因为它不会触发页面刷新。

例如

window.location.href = '#your-anchor-tag';
Run Code Online (Sandbox Code Playgroud)