美文网首页
react.js单页面跳转

react.js单页面跳转

作者: 故林青衫 | 来源:发表于2018-06-25 16:28 被阅读0次

          react.js用js的方式实现页面跳转暂时收录了两种方式。首先路由跳转需由父组件用router={history}方法 将路由信息传递给子组件,而后在子组件绑定点击事件,

       this.props.history.push('/...');
    

          从而实现js控制页面跳转。
    方法一:在同一个组件中,添加绑定事件:

    <Button onClick={this.routePush} router={history}></Button>
    
    routePush(){
        this.props.history.push('/...');
    }
    

    其中很重要的是:

     constructor (props) {
        super(props);
        //关键就是这里,把要使用this的函数  在构造函数中用bind方法传入this
        this.routePush = this.routePush.bind(this);
    }
    

    方法二:在同一组件中,通过路由重定向Redirect进行跳转;

    //引入Redirect 
    import { Redirect } from 'react-router-dom';
    //constructor中初始化字段redirect:false
    this.state = {
            redirect:false
        };
    //点击事件,改变redirect,实现render路由重定向,
    this.setState({ redirect: true });
    //render()内重定向页面路由
    if (this.state.redirect){
        return <Redirect push to="/Protocols" />;
    }
    

    备注:这种方式直接重定向了原来的路由,虽然实现了跳转,但具体是否有其他问题还不确定,暂时未深入了解。

    相关文章

      网友评论

          本文标题:react.js单页面跳转

          本文链接:https://www.haomeiwen.com/subject/bjpyyftx.html