我正在创建一个表单,在填充后单击提交按钮应导航到另一个组件。但是,我似乎无法将历史作为道具。我认为我对这个绑定做错了但是不能解决这个问题。感谢。
这是我的App.js
import React from 'react';
import {BrowserRouter, Route, Switch} from 'react-router-dom';
import {LandingPage} from './landingPage/LandingPage';
import {ReportsPage} from './reportsPage/ReportsPage';
export class App extends React.Component {
render() {
return (
<BrowserRouter >
<Switch>
<Route path="/" exact component={LandingPage}/>
<Route path="/reports"
render={() => <ReportsPage/>}
/>
</Switch>
</BrowserRouter>
);
}
}
这是我的LandingPage.js
export class LandingPage extends React.Component {
constructor(props){
super(props);
this.state = {
...
this.formAnswersUpdater = this.formAnswersUpdater.bind(this)
}
formAnswersUpdater(e) {
e.preventDefault()
...
history.push("/reports")
}
render() {
return (
<div>
...
<MyForm
onClickOnLastInputsForm={e => this.formAnswersUpdater}
/>
</div>
)
}
这是我的活动正在发生的地方。 MyForm.js
export class MyForm extends React.Component {
render() {
return(
...
<Route render={({history}) => (
<button className="uk-button uk-button-primary uk-width-1-1@s"
style={{backgroundColor:'#41f44f',
color:'#666', margin: 0}}
id='buttonSliders'
/*if done here it works*/
/*onClick={() => {history.push("/reports")}}*/
/*However if passed to the event handler it does not*/
onClick={() => {this.props.onClickOnLastInputsForm}}
>
ClickMe!
</button>
)}/>
)
我的react-router-dom版本是:“^ 4.2.2”
答案 0 :(得分:2)
好的,这就是我处理这个问题的方法。
我没有导出LandingPage组件,而是将其包装在withRouter函数中,然后将其导出。
class LandingPage extends React.Component {
constructor(props){
super(props);
this.state = {
...
this.formAnswersUpdater = this.formAnswersUpdater.bind(this)
}
formAnswersUpdater(e) {
e.preventDefault()
...
//added this.props. here
this.props.history.push("/reports")
}
render() {
return (
<div>
...
<MyForm
onClickOnLastInputsForm={e => this.formAnswersUpdater}
/>
</div>
)
}
// wrapped it with withRouter
export default withRouter(LandingPage)
然后在MyForm组件中我调用了eventHandler。
export class MyForm extends React.Component {
render() {
return(
...
<button className="uk-button uk-button-primary uk-width-1-1@s"
style={{backgroundColor:'#41f44f',
color:'#666', margin: 0}}
id='buttonSliders'
onClick={this.props.onClickOnLastInputsForm()}
>
ClickMe!
</button>
)
答案 1 :(得分:0)
我不知道这是否会解决您的所有问题,但我发现LandingPage
渲染功能中缺少一些重要的内容
onClickOnLastInputsForm={e => this.formAnswersUpdater}
你忘了传递你的论点:e
onClickOnLastInputsForm={e => this.formAnswersUpdater(e)}
请务必在MyForm
上添加此内容。你也忘记了它。修好后会有其他错误吗?
编辑:在对文档进行一些检查之后,react-router-dom
的典型用法看起来与您拥有的模式不同。路由处理的最常见模式是拥有一组根路由,并使用npm包中的Link
进行导航。我只在react-router
的文档中看到历史及其衍生物。我知道react-router-dom
是react-router
的衍生物,但我认为如果你遵循React的正常模式,那么将来调试时你会更容易。
一篇很好的文章。它甚至有一个使用它的示例应用程序:https://medium.com/@pshrmn/a-simple-react-router-v4-tutorial-7f23ff27adf