Navigate in code with react

Looking at this video the react router seems easy to use, but I can't find how to navigate in my code since I want to link on clicking a div and not use <Link> .

I've search StackOverflow but haven't found any answers that work with 4.0. Trying to import browserHistory gives undefined (before and after installing 'react-router' in addition to 'react-router-dom') from this question:

import { browserHistory } from 'react-router';
console.log('browserHistory:', browserHistory);

I also saw somewhere that there is a 'context' you can get to, but this shows a value for 'match' but not 'context':

<Route path="/" render={({ match, context}) => {
    console.log('match:', match);
    console.log('context:', context);

Edit

In the dev tools I can see that "Router" has a history property, so when I add that I can get to it:

<Route path="/" render={({ match, context, history}) => {

Is there a way to get to this from outside a route? For example a navbar component that will navigate to other components, but is not inside a Route itself...


如果我理解你的问题,这是你如何进行链接programaticaly。

    class Test extends React.Component {

      handleClick() {
        console.log(this.context);
        this.context.router.history.push('/some/path');
      },

      render() {

        return (
          <div onClick={handleClick}>
            This is div.
          </div>
        )
      }
    }

    Test.contextTypes = {
      router: React.PropTypes.object.isRequired
    }

    ReactDOM.render(
      <Test />,
      document.getElementById("app")
    );

Had to read into the docs more. The history object is only passed as a property using the component (or other) attributes on a Route . Apparently need to include the 'history' package and use createBrowserHistory and pass it to the Router , then specify the component in a Route . I think this should work fine since exact isn't specified...

import { createBrowserHistory } from 'history';
const history = createBrowserHistory();
ReactDOM.render( (
    <Router history={ history }>
      <Route path="/" component={ App } />
    </Router>
  ),
  document.getElementById('root')
);

Before I just had <App/> inside <Router> and didn't have access to those properties.


你为什么不把自己的div封装在链接中,而不是试图规避它,让你的生活更轻松?

    <Link to="/" >
       <div className="to-component">go to component</div>
    </Link>
链接地址: http://www.djcxy.com/p/52138.html

上一篇: 以编程方式反应路由器v4导航

下一篇: 用代码导航进行反应