简体   繁体   English

为什么我不能在表单输入(子组件)和 React useState Hook(父组件)之间共享信息?

[英]Why I cant share info between form input (child component) and React useState Hook (parent component)?

I am doing a multiple step form with React and I expect that when the user hits "Next" button, he/she can go to the next form, save info in parent component useState Hook and keep it in the input if user decides to go back.我正在使用 React 做一个多步骤表单,我希望当用户点击“下一步”按钮时,他/她可以 go 到下一个表单,如果用户决定使用 go 将信息保存在父组件 useState Hook 中并将其保留在输入中背部。 Switch has 8 cases but I left only 1 for simplicity. Switch 有 8 个案例,但为了简单起见,我只留下了 1 个。 Structure looks something like this (Questions after code):结构看起来像这样(代码后的问题):

<MainForm /> |_ <UserInfo /> |_ Another 7 childs

MainForm.js MainForm.js

import React, { useState } from "react";

import UserInfo from "../components/Shared/UserInfo";
//import ... more childs ...
import {
  BackButton,
  NextButton,
  SendButton,
} from "../components/Shared/Buttons";

const BDMForm = (props) => {
  const [step, setStep] = useState(1);
  const [datos, setDatos] = useState({
    fullName: "",
    email: "",
    phoneNumber: "",
    linkedIn: "",
    city: "",
    experience: "",
  });

  const handleChange = (e) => {
    setDatos({ ...datos, [e.target.name]: e.target.value });
  };
  function renderComponent(step) {
    let currentStep = step;

    switch (currentStep) {
      case 1:
        return <UserInfo handleChange={handleChange} datos={datos.fullName} />;

      // 7 more cases
}
  return (
    <form>
      {renderComponent(step)}
      <div className="button-container">
        <BackButton step={step} setStep={setStep} />
        {step >= 7 ? null : <NextButton step={step} setStep={setStep} />}
        {step === 7 ? <SendButton /> : null}
      </div>
    </form>
  );
};

export default MainForm;

UserInfo.js用户信息.js

import React from "react";

  return (
        <div className="card-container">
          <label>
            Nombre y Apellido<span> *</span>
          </label>
          <input
            type="text"
            name="fullName"
            value={props.datos}
            onChange={props.handleChange}
          />
        </div>
      </div>
  );
};

export default UserInfo;

I have 2 questions:我有两个问题:

1) When I write something on fullName input (UserInfo.js), I think React is updating the component with the default value ("") so I cant write anything on it. 1)当我在全名输入(UserInfo.js)上写一些东西时,我认为 React 正在使用默认值(“”)更新组件,所以我不能在上面写任何东西。 Expected behavior: User can write and input should be saved in datos.fullName on parent component.预期行为:用户可以写入,输入应保存在父组件的 datos.fullName 中。 When user press Next or back, written information will still be there.当用户按 Next 或 back 时,书面信息仍然存在。

2) Is my approach OK? 2)我的方法好吗? Should I be saving all children data in parent component and then access it from another child later on (Like Confirm.js or somewhere where the user can read the information before send it).我是否应该将所有子数据保存在父组件中,然后稍后从另一个子组件访问它(例如 Confirm.js 或用户可以在发送之前读取信息的地方)。 I tried to learn Context API but still don't understand how to implement it我试图学习 Context API 但仍然不明白如何实现它

Change your handleChange function like this:像这样改变你的handleChange function:

  const handleChange = (e) => {
    const fieldName = e.target.name;
    const fieldValue = e.target.value;
    setDatos(prevDatos => ({ ...prevDatos, [fieldName]: fieldValue }));
  };

When the new state depends on the previous state you have to use the functional way to update the state.当新的 state 依赖于以前的 state 时,您必须使用功能方式更新 state。

Regarding your second question, yes, your approach is fine.关于你的第二个问题,是的,你的方法很好。

And finally, I would maintain some consistency when defining the functions.最后,我会在定义函数时保持一定的一致性。 I'm referring to handleChange and renderComponent functions.我指的是handleChangerenderComponent函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM