在表单设计中,经常需要多步表单。用户在不同的步骤填写不同的内容,最后一起提交。其基本思路就是设计一个总控表单组件,然后将对应的状态及更改状态的方法传递给其子组件,这样在子组件中的字段发生变化时,就会更新父表单状态,因此在最后父表单提交时就可以将子表单的字段一同提交了。

React表单组件
React表单系列
创建父表单组件
首先创建父组件src/components/MasterForm.js。在父组件中定义了username, password, email, currentStep四个状态。然后会分别把username, password, email传递给三个子组件:Step1, Step2, Step3。
javascript
import { useState } from 'react'
import Step1 from './Step1';
import Step2 from './Step2';
import Step3 from './Step3';
export default function MasterForm() {
const [username,setUsername] = useState('');
const [password, setPassword] = useState('');
const [email,setEmail] = useState('');
const [currentStep, setCurrentStep] = useState(1);
const handleSubmit = e => {
e.preventDefault()
console.log(`Your registration detail: \n
Username: ${username} \n
Password: ${password} \n
Email: ${email}
`)
}
const handleNext = () => {
let step = currentStep >= 2? 3: currentStep + 1
setCurrentStep(step)
}
const handlePrevious = () => {
let step = currentStep <= 1? 1: currentStep - 1
setCurrentStep(step)
}
const nextButton = () => {
if(currentStep < 3) {
return (
<button type="button" onClick={handleNext}>
Next
</button>
)
} else {
return null;
}
}
const previousButton = () => {
if(currentStep > 1) {
return (
<button type="button" onClick={handlePrevious}>
Previous
</button>
)
} else {
return null;
}
}
return (
<>
<h1>Form with multiple steps</h1>
<p>Step {currentStep}</p>
<form onSubmit={handleSubmit}>
<Step1 currentStep={currentStep}
username={username}
setUsername={setUsername}/>
<Step2 currentStep={currentStep}
password={password}
setPassword={setPassword}/>
<Step3 currentStep={currentStep}
email={email}
setEmail={setEmail}/>
{previousButton()}
{nextButton()}
<button type="submit">Submit</button>
</form>
</>
)
}创建子组件
以src/components/Step1.js为例:
javascript
import React from 'react'
export default function Step1(props) {
const {currentStep, username, setUsername} = props;
if(currentStep !== 1) {
return null
}
return (
<div>
<label htmlFor="username">Username</label>
<input
id="username"
name="username"
type="text"
placeholder="Enter username"
value={username}
onChange={e => setUsername(e.target.value)}
/>
</div>
)
}测试
其运行效果如下图所示:

React表单
提交时会在控制台输出三个子表单中的字段值:

React表单