React中如何获取子Input组件的状态并赋值给父组件的user对象
Got it, let's fix this. The issue right now is that each of your Input components is managing its own local state, which means your parent Form component can't access those values to update the user object. We need to lift the state up to the parent component and turn your Input into a controlled component—here's how to do it step by step:
Step 1: Convert the user object to parent state
First, your original user is a static object, so we need to make it a state variable so we can update it as the user types. Replace the static user with a useState hook:
const Form = ({ form }) => { // Initialize user state with your default values const [user, setUser] = useState({ user_firstname: "OO", user_lastname: "OO", user_email: "lOOl0jyyv", user_password: "OO", user_verify_password: "" // Add this to track confirm password }); // Remove the unused inputValue state since we'll use user instead // const [inputValue, setInputValue] = useState(""); // ... rest of the code };
Step 2: Create a shared input change handler in the parent
We'll make a single function that updates the user state based on which input is changed. This works by mapping the input's name to the corresponding key in the user object (matching your existing input names):
const handleInputChange = (e) => { const { name, value } = e.target; // Map input names to user object keys const fieldMapping = { firstname: "user_firstname", lastname: "user_lastname", email: "user_email", password: "user_password", "verify-password": "user_verify_password" }; // Update the user state immutably setUser(prevUser => ({ ...prevUser, [fieldMapping[name]]: value })); };
Step 3: Update the Input component to be controlled
Remove the local state from Input and instead accept value and onChange as props from the parent. This way, the parent is fully in control of the input's value:
const Input = ({ className, type, id, name, placeholder, min, max, icon1, icon2, value, onChange }) => { // No need for local inputValue state anymore // const [inputValue, setInputValue] = useState(""); // const inputHandler = e => { setInputValue(e.target.value); }; return ( <div className={className}> <input className="testt" type={type} id={id} name={name} placeholder={placeholder} minLength={min} maxLength={max} required value={value} onChange={onChange} /> {icon1 && ( <div className="icons_container"> <FontAwesomeIcon icon={icon1} /> <FontAwesomeIcon icon={icon2} /> </div> )} </div> ); };
Step 4: Pass the correct props to each Input in the Form
Now, for each Input, pass the corresponding value from the user state and the shared handleInputChange function:
return ( <form className="form" onSubmit={(e) => { e.preventDefault(); // Now you can use the user state in your callApi function callApi(user); }}> <Input key={uuidv4()} className="input_container" type="text" placeholder="Prénom" id="firstname" name="firstname" min="2" max="40" value={user.user_firstname} onChange={handleInputChange} /> <Input key={uuidv4()} className="input_container" type="text" placeholder="Nom" id="lastname" name="lastname" min="2" max="60" value={user.user_lastname} onChange={handleInputChange} /> <Input key={uuidv4()} className="input_container" type="email" placeholder="Votre adresse mail" id="email" name="email" value={user.user_email} onChange={handleInputChange} /> <Input key={uuidv4()} className="input_container" type="password" placeholder="Mot de passe" id="password" name="password" min="10" max="32" value={user.user_password} onChange={handleInputChange} /> <Input key={uuidv4()} className="input_container" type="password" placeholder="Confirmez le mot de passe" id="verify-password" name="verify-password" min="10" max="32" value={user.user_verify_password} onChange={handleInputChange} /> <Button name="Inscription" /> </form> );
Why this works:
- State Lifting: By moving the input state up to the parent
Formcomponent, we centralize control over all form values, making it easy to access the fulluserobject when submitting the form. - Controlled Components: Each
Inputnow receives its value and change handler from the parent, ensuring the UI always reflects the parent state—this follows React's one-way data flow principle. - Reusable Handler: The single
handleInputChangefunction works for all inputs, keeping your code DRY (Don't Repeat Yourself).
Now when the user types into any input, the user state in the parent will update automatically, and you can use this state in your callApi function when the form is submitted.
内容的提问来源于stack exchange,提问作者vincent05996

