gpt4 book ai didi

javascript - 如何使 React 多步骤表单与 React Router 一起工作?

转载 作者:行者123 更新时间:2023-11-29 21:09:18 26 4
gpt4 key购买 nike

我正在努力学习 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>
);
}
});

最佳答案

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

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

然而,React Router 将更新 Prop 并触发渲染。如果您想根据 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>

单击该按钮将导航到下一页。 locationhistory Prop 由 React 路由器插入 Route 组件。

关于javascript - 如何使 React 多步骤表单与 React Router 一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42472469/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com