我正在尝试创建一个多步骤表单,在单击下一个和之前的四个组件之间切换时(此时我不想传递任何数据,只是查看页面)。我已经制作了开关盒但现在我不知道如何返回第一个组件。由于我正在使用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;
此时我应该看到第一个组件渲染
答案 0 :(得分:0)
而不是getInitialState()
,在构造函数本身中添加step
属性:
constructor () {
super();
this.state = {
allInputs: [],
step: 1
}
}
如果依赖于先前状态的下一个状态,也可以使用函数setState,因为setState is async。例如:将您的功能转换为:
nextStep() {
this.setState((prevState) => ({ step: prevState.step + 1 }))
}