【发布时间】:2017-11-03 08:37:55
【问题描述】:
我正在尝试创建一个多步骤表单,该表单在单击下一个和上一个组件时会在四个组件之间切换(此时我对传递任何数据不感兴趣,只是查看页面)。我已经制作了开关盒,但现在我不知道如何返回第一个组件。由于我使用的是 create-react-app ,因此我正在按照此示例进行修改:https://github.com/tommymarshall/react-multi-step-form/blob/master/src/javascript/components/Registration.jsx
这是我的代码:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import PageOne from './PageOne';
import PageTwo from './PageTwo';
import PageThree from './PageThree';
import PageFour from './PageFour';
class Form extends Component {
constructor () {
super();
this.state = {
allInputs: []
}
}
componentWillMount () {
this.setState({allInputs: []})
}
getInitialState() {
return {
step: 1
}
}
saveValues(input) {
let allInputs = this.state.allInputs;
allInputs.push(input);
this.setState({allInputs:allInputs});
}
nextStep() {
this.setState({
step: this.state.step +1
})
}
previousStep() {
this.setState({
step : this.state.step - 1
})
}
submitRegistration() {this.nextStep()}
showStep() {
switch (this.state.step) {
case 1:
return <PageOne
nextStep={this.nextStep}
previousStep={this.previousStep}
saveValues={this.saveValues} />
case 2:
return <PageTwo
nextStep={this.nextStep}
previousStep={this.previousStep}
saveValues={this.saveValues} />
case 3:
return <PageThree
nextStep={this.nextStep}
previousStep={this.previousStep}
saveValues={this.saveValues} />
case 4:
return <PageFour
previousStep={this.previousStep}
submitRegistration={this.submitRegistration} />
}
}
render() {
return (
<div className="Form">
{this.showStep()}
</div>
);
}
}
export default Form;
此时我应该看到第一个组件渲染
【问题讨论】:
-
删除
getInitialState,将step: 1添加到构造函数内的this.state对象中。getInitialState函数在 ES6 类中已弃用,只能与React.createClass一起使用。 -
@Dan 谢谢你成功了!关于如何跟踪我进行的步骤的任何建议?
-
跟上文档并阅读 React (reactjs.org/blog) 的博客文章是一个很好的开始。
标签: javascript reactjs switch-statement