如何使React多步骤表单与React Router一起使用?

问题描述 投票:0回答:1

我正在努力学习React + ReactRouter来构建一个多步骤的表单。我在这里工作的例子:https://www.viget.com/articles/building-a-multi-step-registration-form-with-react

问题是此示例不使用ReactRouter,因此URL在表单期间永远不会更改。作者提到“您可以将每个步骤设置为自定义路线”但是,我无法弄清楚如何使其工作。如何更新当前渲染过程以使用ReactRouter?

render: function() {
    switch (this.state.step) {
        case 1:
    return <AccountFields fieldValues={fieldValues}
                          nextStep={this.nextStep}
                          saveValues={this.saveValues} />
        case 2:
    return <SurveyFields  fieldValues={fieldValues}
                          nextStep={this.nextStep}
                          previousStep={this.previousStep}
                          saveValues={this.saveValues} />
        case 3:
    return <Confirmation  fieldValues={fieldValues}
                          previousStep={this.previousStep}
                          submitRegistration={this.submitRegistration} />
        case 4:
    return <Success fieldValues={fieldValues} />
    }
}

我试过了:

  render: function() {
        switch (this.state.step) {
            case 1:
        return <AccountFields fieldValues={fieldValues}
                              nextStep={this.nextStep}
                              saveValues={this.saveValues} />
            case 2:
                       browserHistory.push('/surveyfields')
            case 3:
                      browserHistory.push('/confirmation')
            case 4:
                       browserHistory.push('/success')
        }
    }

更新

..
        case 2:
            <Route path="/surveyfields" component={SurveyFields}/>
..

var Welcome = React.createClass({
  render() {
    return (
      <Router history={browserHistory}>
        <Route path='/welcome' component={App}>
          <IndexRoute component={Home} />
          <Route path='/stuff' component={Stuff} />
          <Route path='/features' component={Features} />
          <Route path='/surveyfields' component={SurveyFields} />

        </Route>
      </Router>
    );
  }
});
javascript reactjs react-router
1个回答
1
投票

如果你像这样路由它们,从/surveyfields转换到/success不会影响Survey组件的状态。

<Route path="/surveyfields" component={Survey}/>
<Route path="/confirmation" component={Survey}/>
<Route path="/success" component={Survey}/>

但是,React Router会更新道具并触发渲染。如果你想根据URL渲染不同的东西,请在render方法中使用它。

if(this.props.location.pathname==="/surveyfields")
   return (
     <span>
       survey things
       <Button onClick={() => this.props.history.push("/confirmation")}>next page</Button>
   </span>)
if(this.props.location.pathname==="/confirmation")
   return <span>do you want to do this</span>

单击该按钮将导航到下一页。 qactxswpoi和location道具由React路由器插入路由组件。

© www.soinside.com 2019 - 2024. All rights reserved.