首页 文章

React-router:如何手动调用链接?

提问于
浏览
78

我是ReactJS和React-Router的新手 . 我有一个组件通过道具接收来自 react-router<Link/> 对象 . 每当用户单击此组件内的'next'按钮时,我想手动调用 <Link/> 对象 .

现在,我正在使用refs访问 backing instance 并手动点击 <Link/> 生成的'a'标签 .

Question: 有没有办法手动调用链接(例如 this.props.next.go )?

这是我目前的代码:

//in MasterPage.js
var sampleLink = <Link to="/sample">Go To Sample</Link>
<Document next={sampleLink} />

//in Document.js
...
var Document = React.createClass({
   _onClickNext: function() {
      var next = this.refs.next.getDOMNode();
      next.querySelectorAll('a').item(0).click(); //this sounds like hack to me
   },
   render: function() {
      return (
         ...
         <div ref="next">{this.props.next} <img src="rightArrow.png" onClick={this._onClickNext}/></div>
         ...
      );
   }
});
...

这是我想要的代码:

//in MasterPage.js
var sampleLink = <Link to="/sample">Go To Sample</Link>
<Document next={sampleLink} />

//in Document.js
...
var Document = React.createClass({
   render: function() {
      return (
         ...
         <div onClick={this.props.next.go}>{this.props.next.label} <img src="rightArrow.png" /> </div>
         ...
      );
   }
});
...

6 回答

  • 140

    React Router v4 - 重定向组件(更新2017/04/15)

    v4推荐的方法是允许渲染方法捕获重定向 . 使用state或props来确定是否需要显示重定向组件(然后触发重定向) .

    import { Redirect } from 'react-router';
    
    // ... your class implementation
    
    handleOnClick = () => {
      // some action...
      // then redirect
      this.setState({redirect: true});
    }
    
    render() {
      if (this.state.redirect) {
        return <Redirect push to="/sample" />;
      }
    
      return <button onClick={this.handleOnClick} type="button">Button</button>;
    }
    

    参考:https://reacttraining.com/react-router/web/api/Redirect

    React Router v4 - 参考路由器上下文

    您还可以利用暴露于React组件的 Router 's context that' .

    static contextTypes = {
      router: PropTypes.shape({
        history: PropTypes.shape({
          push: PropTypes.func.isRequired,
          replace: PropTypes.func.isRequired
        }).isRequired,
        staticContext: PropTypes.object
      }).isRequired
    };
    
    handleOnClick = () => {
      this.context.router.push('/sample');
    }
    

    这就是 <Redirect /> 在幕后工作的方式 .

    参考:https://github.com/ReactTraining/react-router/blob/master/packages/react-router/modules/Redirect.js#L46,L60

    React Router v4 - 外部变异历史对象

    如果您仍需要执行与v2实现类似的操作,则可以创建 BrowserRouter 的副本,然后将 history 公开为可导出常量 . 下面是一个基本的例子,但如果需要,你可以编写它以注入可定制的道具 . 有生命周期的注意事项,但它应该总是重新渲染路由器,就像在v2中一样 . 这对于来自动作函数的API请求后的重定向非常有用 .

    // browser router file...
    import createHistory from 'history/createBrowserHistory';
    import { Router } from 'react-router';
    
    export const history = createHistory();
    
    export default class BrowserRouter extends Component {
      render() {
        return <Router history={history} children={this.props.children} />
      }
    }
    
    // your main file...
    import BrowserRouter from './relative/path/to/BrowserRouter';
    import { render } from 'react-dom';
    
    render(
      <BrowserRouter>
        <App/>
      </BrowserRouter>
    );
    
    // some file... where you don't have React instance references
    import { history } from './relative/path/to/BrowserRouter';
    
    history.push('/sample');
    

    最新 BrowserRouter 延期:https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/modules/BrowserRouter.js

    React Router v2

    将新状态推送到 browserHistory 实例:

    import {browserHistory} from 'react-router';
    // ...
    browserHistory.push('/sample');
    

    参考:https://github.com/reactjs/react-router/blob/master/docs/guides/NavigatingOutsideOfComponents.md

  • 3

    React Router 4包含withRouter HOC,可让您通过 this.props 访问 history 对象:

    import React from 'react'
    import {withRouter} from 'react-router-dom'
    
    class Foo extends Component {
      constructor(props) {
        super(props)
    
        this.goHome = this.goHome.bind(this)
      }
    
      goHome() {
        this.props.history.push('/')
      }
    
      render() {
        <div className="foo">
          <button onClick={this.goHome} />
        </div>
      }
    }
    
    export default withRouter(Foo)
    
  • 56

    https://github.com/rackt/react-router/blob/bf89168acb30b6dc9b0244360bcbac5081cf6b38/examples/transitions/app.js#L50

    或者你甚至可以尝试执行onClick这个(更暴力的解决方案):

    window.location.assign("/sample");
    
  • 2

    好吧,我想我能找到一个合适的解决方案 .

    现在,我不发送 <Link/> 作为 prop 给Document,而是发送 <NextLink/> ,它是react-router Link的自定义包装器 . 通过这样做,我可以将右箭头作为Link结构的一部分,同时仍然避免在Document对象中包含路由代码 .

    更新的代码如下所示:

    //in NextLink.js
    var React = require('react');
    var Right = require('./Right');
    
    var NextLink = React.createClass({
        propTypes: {
            link: React.PropTypes.node.isRequired
        },
    
        contextTypes: {
            transitionTo: React.PropTypes.func.isRequired
        },
    
        _onClickRight: function() {
            this.context.transitionTo(this.props.link.props.to);
        },
    
        render: function() {
            return (
                <div>
                    {this.props.link}
                    <Right onClick={this._onClickRight} />
                </div>  
            );
        }
    });
    
    module.exports = NextLink;
    
    ...
    //in MasterPage.js
    var sampleLink = <Link to="/sample">Go To Sample</Link>
    var nextLink = <NextLink link={sampleLink} />
    <Document next={nextLink} />
    
    //in Document.js
    ...
    var Document = React.createClass({
       render: function() {
          return (
             ...
             <div>{this.props.next}</div>
             ...
          );
       }
    });
    ...
    

    P.S :如果您使用的是最新版本的react-router,则可能需要使用 this.context.router.transitionTo 而不是 this.context.transitionTo . 此代码适用于react-path版本0.12.X.

  • 2

    React Router 4

    您可以通过v4中的上下文轻松调用push方法:

    this.context.router.push(this.props.exitPath);

    上下文是:

    static contextTypes = {
        router: React.PropTypes.object,
    };
    
  • 0

    再次这是JS :)这仍然有效....

    var linkToClick = document.getElementById('something');
    linkToClick.click();
    
    <Link id="something" to={/somewhaere}> the link </Link>
    

相关问题