【问题标题】:Creating a multi-step/component form using switch statement使用 switch 语句创建多步骤/组件表单
【发布时间】: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


【解决方案1】:

在构造函数本身内添加step 属性,而不是getInitialState()

constructor () {
    super();
    this.state = {
      allInputs: [],
      step: 1
    }
}

如果您依赖前一个状态来获取下一个状态,也可以使用函数式 setState,因为 setState is async。例如:转换您的功能,如:

nextStep() {
    this.setState((prevState) => ({ step: prevState.step + 1 }))
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-18
    • 1970-01-01
    相关资源
    最近更新 更多