我在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中?那么有人可以帮助我吗?
提前致谢。
我有同样的问题,并发现你通过在<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>
)
}
}
而不是将Link
放在button
中,您可以通过使用传递给给予history
的组件的Route
prop来以编程方式更改URL。
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
的component
道具中使用该组件。
<Route path='/home' component={Home} />