简体   繁体   English

如何使用 react-select 以多步形式在多选下拉列表中设置默认值

[英]How to set default value in multiselect dropdown in multistep form with react-select

I am currently working on a multistep form with multiselect dropdowns with react-select.我目前正在使用带有 react-select 的多选下拉菜单制作多步表单。 Everything works so far, except when switching between steps, the dropdown fields are not filled with the values of the current state.到目前为止一切正常,除了在步骤之间切换时,下拉字段没有填充当前状态的值。

// CreateForm.js

function CreateForm() {
  const [selectedValue, setSelectedValue] = useState({
    profile_name: "",
    car: "",
  });

  const [step, setStep] = useState(1);

  const nextStep = () => {
    if (step < 2) {
      setStep(step + 1);
    } else if (step === 2) {
      console.log(selectedValue);
    }
  };

  const prevStep = () => {
    if (step > 1) {
      setStep(step - 1);
    }
  };

  const handleChange = (name) => (e) => {
    setSelectedValue((prevState) => ({
      ...prevState,
      [name]: Array.isArray(e) ? e.map((x) => x.value) : [],
    }));
    console.log(selectedValue);
  };

  return (
    <div className="bg-dark vh-100 text-light">
      <div className="d-flex flex-column justify-content-center">
        <div>
          {
            {
              1: (
                <CreateFormFirstStep
                  handleChange={handleChange}
                  optionSelected={selectedValue}
                />
              ),
              2: (
                <CreateFormSecondStep
                  handleChange={handleChange}
                />
              ),
            }[step]
          }
        </div>
      </div>
      <div className="d-flex flex-row justify-content-around px-5 mt-5">
        {step > 1 ? (
          <button className="btn btn-secondary" onClick={prevStep}>
            Back
          </button>
        ) : null}
        <button className="btn btn-primary" onClick={nextStep}>
          {step === 2 ? "Save" : "Next"}
        </button>
      </div>
    </div>
  );
}

export default CreateForm;

// CreateFormFirstStep

const CreateFormFirstStep = ({ handleChange }, selectedValue ) => {
  const data = [
  { value: 'bugatti', label: 'Bugatti' },
  { value: 'ferrari', label: 'Ferrari' },
  { value: 'am', label: 'Aston Martin' },
  { value: 'koenigsegg', label: 'Koenigsegg' },
  { value: 'bmw', label: 'BMW' },
  { value: 'cadillac', label: 'Cadillac' },
];
  return (
    <div className="CreateFormFirstStep">
      <h3>Test name</h3>
            <Select
              className="text-dark"
              style={{ display: "flex", flexDirection: "column" }}
              placeholder="Choose..."
              options={data}
              isMulti
              closeMenuOnSelect={false}
              hideSelectedOptions={false}
              isLoading={!data}
              onChange={handleChange("car")}
              defaultValue={selectedValue.car}
              selectedValue={selectedValue.car}
              name={"car"}
            />
    </div>
  );
};

export default CreateFormFirstStep;

So when switching between the two steps in the form, the chosen values are not preset in the select field.所以在表单中的两个步骤之间切换时,选择的值不会预设在选择字段中。 However as seen in the console, the state is saved correctly.但是,如控制台中所见,状态已正确保存。 How do I fill the Select field with the current state values when switching between steps?在步骤之间切换时,如何使用当前状态值填充 Select 字段? Help is very much appreciated.非常感谢您的帮助。

I found the error in the handleChange function.我在 handleChange 函数中发现了错误。 It should save the state as an object with value and label instead of an array:它应该将状态保存为具有值和标签的对象,而不是数组:

  const handleChange = (name) => (e) => {
    setSelectedValue((prevState) => ({
      ...prevState,
      [name]: e.map((x) => ({
        value: x.value,
        label: x.label,
      })),
    }));
    console.log(selectedValue);
  };

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

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