使用react router,我可以使用Link元素来创建由react route本地处理的链接。

我看到它在内部调用this.context.transitionTo(…)。

我想做导航。不是来自链接,而是来自下拉选择(例如)。我如何在代码中执行此操作?this.context是什么?

我看到了导航混合,但我可以在没有混合的情况下这样做吗?


当前回答

您可以在React中尝试onClick事件,并使用React Router的useNavigate钩子调用函数重定向到指定位置。您可以直接在onClick处理程序中使用回调函数,而不是指定其他函数。首先需要安装react router DOM。

npm i react-router-dom

尝试以下代码

import { useNavigate } from "react-router-dom";

const Page = () => {
  const navigate = useNavigate();

  return (
    <button onClick={() => navigate('/pagename')}>
      Go To Page
    </button>
  );
}

其他回答

对于这一个,谁不控制服务器端,因此使用哈希路由器v2:

将历史记录放入单独的文件(例如app_history.js ES6):

import { useRouterHistory } from 'react-router'
import { createHashHistory } from 'history'
const appHistory = useRouterHistory(createHashHistory)({ queryKey: false });

export default appHistory;

并在任何地方使用它!

react router(app.js ES6)的入口点:

import React from 'react'
import { render } from 'react-dom'
import { Router, Route, Redirect } from 'react-router'
import appHistory from './app_history'
...
const render((
  <Router history={appHistory}>
  ...
  </Router>
), document.querySelector('[data-role="app"]'));

任何组件(ES6)内的导航:

import appHistory from '../app_history'
...
ajaxLogin('/login', (err, data) => {
  if (err) {
    console.error(err); // login failed
  } else {
    // logged in
    appHistory.replace('/dashboard'); // or .push() if you don't need .replace()
  }
})

对于最新的反应路由器dom v6

useHistory()替换为useNavigate()。

您需要使用:

import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();
navigate('/your-page-link');

带挂钩的React Router v6

import {useNavigate} from 'react-router-dom';
let navigate = useNavigate();
navigate('home');

为了浏览浏览器历史,

navigate(-1); ---> Go back
navigate(1);  ---> Go forward
navigate(-2); ---> Move two steps backward.

以下是如何使用带有ES6的react router v2.0.0来实现这一点。react路由器已远离mixin。

import React from 'react';

export default class MyComponent extends React.Component {
  navigateToPage = () => {
    this.context.router.push('/my-route')
  };

  render() {
    return (
      <button onClick={this.navigateToPage}>Go!</button>
    );
  }
}

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

React路由器v4和ES6

您可以使用Router和this.props.history.push。

import {withRouter} from 'react-router-dom';

class Home extends Component {

    componentDidMount() {
        this.props.history.push('/redirect-to');
    }
}

export default withRouter(Home);