You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ReactJS中用按钮遍历JSON实现多步骤表单

React多步骤表单实现指南

核心逻辑很简单:用React的状态管理当前显示的问题索引,加载你的JSON数据后,根据索引渲染对应内容,点击Next按钮时更新索引,同时处理边界情况(比如到最后一页时禁用按钮)。下面是具体实现步骤和代码:

1. 准备数据与初始化状态

先把你的JSON数据保存为formQuestions.json文件,然后在组件中导入。用useState定义两个核心状态:一个存当前页面的索引(初始为0,对应第一个问题),另一个直接使用导入的表单数据。

import { useState } from 'react';
import formQuestions from './formQuestions.json';

export default function MultiStepForm() {
  // 用state管理当前问题的索引,初始值0对应第一个问题
  const [currentPageIndex, setCurrentPageIndex] = useState(0);
  // 获取当前要展示的问题对象
  const currentQuestion = formQuestions[currentPageIndex];

2. 渲染当前问题内容

根据currentQuestion渲染问题文本、页码标记,以及必填提示,同时可以添加对应的表单输入控件:

return (
    <div className="form-container">
      <div className="question-card">
        <h3>第 {currentQuestion.page} 步</h3>
        <p>
          {currentQuestion.question}
          {/* 显示必填星号 */}
          {currentQuestion.required === 'true' && <span style={{ color: 'red', marginLeft: '4px' }}>*</span>}
        </p>
        {/* 这里可以替换为你需要的表单控件:文本框、单选框、下拉选等 */}
        <input type="text" placeholder="请输入答案" />
      </div>

3. 实现Next按钮逻辑

编写点击事件处理函数,判断是否还有下一页,有则更新索引;最后一页时禁用按钮并修改文案:

<div className="button-group">
        <button
          onClick={() => {
            // 防止越界,只有当前不是最后一页时才切换
            if (currentPageIndex < formQuestions.length - 1) {
              setCurrentPageIndex(prevIndex => prevIndex + 1);
            }
          }}
          disabled={currentPageIndex === formQuestions.length - 1}
        >
          {currentPageIndex === formQuestions.length - 1 ? '完成' : 'Next'}
        </button>
      </div>
    </div>
  );
}

完整可运行代码

整合所有部分,加上基础样式的完整组件代码:

import { useState } from 'react';
import formQuestions from './formQuestions.json';

export default function MultiStepForm() {
  const [currentPageIndex, setCurrentPageIndex] = useState(0);
  const currentQuestion = formQuestions[currentPageIndex];

  const handleNext = () => {
    if (currentPageIndex < formQuestions.length - 1) {
      setCurrentPageIndex(prev => prev + 1);
    }
  };

  return (
    <div style={{ maxWidth: '600px', margin: '2rem auto', padding: '0 1rem' }}>
      <div style={{ marginBottom: '2rem' }}>
        <h2>多步骤表单</h2>
        <p>进度:{currentPageIndex + 1}/{formQuestions.length}</p>
      </div>

      <div style={{ padding: '1.5rem', border: '1px solid #eee', borderRadius: '8px' }}>
        <h3>问题 {currentQuestion.page}</h3>
        <p style={{ fontSize: '1.1rem', margin: '1rem 0' }}>
          {currentQuestion.question}
          {currentQuestion.required === 'true' && <span style={{ color: '#dc2626' }}>*</span>}
        </p>
        <input
          type="text"
          style={{ width: '100%', padding: '0.8rem', border: '1px solid #ddd', borderRadius: '4px' }}
          placeholder="请输入你的答案"
        />
      </div>

      <div style={{ marginTop: '2rem', textAlign: 'right' }}>
        <button
          onClick={handleNext}
          disabled={currentPageIndex === formQuestions.length - 1}
          style={{
            padding: '0.8rem 1.5rem',
            backgroundColor: currentPageIndex === formQuestions.length - 1 ? '#ccc' : '#2563eb',
            color: '#fff',
            border: 'none',
            borderRadius: '4px',
            cursor: currentPageIndex === formQuestions.length - 1 ? 'not-allowed' : 'pointer'
          }}
        >
          {currentPageIndex === formQuestions.length - 1 ? '完成' : 'Next'}
        </button>
      </div>
    </div>
  );
}

关键部分解释

  • 状态管理:currentPageIndex是核心,它的变化会触发React重新渲染组件,自动切换到对应索引的问题。
  • 数据访问:导入的JSON会被自动解析为JavaScript数组,直接通过索引formQuestions[currentPageIndex]就能拿到当前问题对象。
  • 边界处理:判断currentPageIndex < formQuestions.length - 1,避免数组越界;最后一页禁用按钮,同时把文案改成“完成”,符合用户预期。
  • 必填提示:根据required字段的值动态显示红色星号,提示用户该问题为必填项。

扩展建议

  • 要加“上一步”按钮,只需写一个类似的handlePrev函数,判断currentPageIndex > 0时减少索引即可。
  • 可以添加表单验证逻辑,比如必填项未填写时,阻止切换到下一页并给出提示。
  • 如果JSON数据是从后端API获取的,需要用useEffect钩子发起请求,请求完成后再把数据存入状态。

内容的提问来源于stack exchange,提问作者Safwan Parkar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 19:15:48