在firefox中react-router-dom的链接不起作用

时间:2018-08-03 04:08:51

标签: javascript reactjs react-router react-router-dom

我的routes.js文件中包含以下代码

import React, { Component } from 'react'
import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom'
import Home from './components/home/Home.jsx'
import Dashboard from './components/dashboard/Dashboard.jsx'
import { browserHistory } from 'react-router'

class Routes extends Component {
  render () {
    return (
      <Router history={browserHistory}>
        <div>
          <Switch>
            <Route path='/home' component={() => (<Home />)} />
            <Route path='/dashboard' component={() => (<Dashboard />)} />
            <Redirect to={{pathname: '/home'}} />
          </Switch>
        </div>
      </Router>
    )
  }
}

export default Routes

然后是我的Home.jsx

import React, { Component } from 'react'
import {Link} from 'react-router-dom'

class Home extends Component {
  render () {
    return (
      <div>
        <h1>This is a home page.</h1>
        <button>
          <Link to='/dashboard'>Click here (Dashboard)</Link>
        </button>
      </div>
    )
  }
}

export default Home

但是,如果我单击Home.jsx中存在的按钮,则它在chrome和safari中可以正常工作,并将我重定向到Dashboard页面,但这是(“ Home.jsx”中的此按钮)在Firefox中没有响应。而且我不明白它会卡在Firefox中吗?那么有人可以帮我吗?

谢谢。

2 个答案:

答案 0 :(得分:3)

您可以使用传递给给Link的组件的button道具,以编程方式更改url,而不是将history放在Route内。

class Home extends Component {
  handleClick = () => {
    this.props.history.push('/dashboard');
  };

  render () {
    return (
      <div>
        <h1>This is a home page.</h1>
        <button onClick={this.handleClick}>
          Click here (Dashboard)
        </button>
      </div>
    )
  }
}

要确保为Home组件赋予route props,必须直接在Route的{​​{1}}属性中使用该组件。

component

答案 1 :(得分:1)

我遇到了同样的问题,发现您通过将<button>嵌套在<Link>中来使其在Firefox中工作:

class Home extends Component {
  render () {
    return (
      <div>
        <h1>This is a home page.</h1>
        <Link to="/dashboard">
          <button>
            Click here (Dashboard)
          </button>
        </Link>
      </div>
    )
  }
}