首页 > 解决方案 > 选择组件渲染

问题描述

我在反应中制作了一个自定义选择组件,它看起来像这样:

import { useDispatch, useSelector } from "react-redux";

const Select = ({
  id,
  options,
  dispatchKey,
  selector,
  disabledOption = false,
}) => {
  const dispatch = useDispatch();
  const formValue = useSelector((state) => state.form[selector]);

  return (
    <select
      id={id}
      required
      onChange={(e) => dispatch({ type: dispatchKey, value: e.target.value })}
      value={'IT'}
      className="mt-1 block form-select w-full py-2 px-3 py-0 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:shadow-outline-blue focus:border-blue-300 transition duration-150 ease-in-out sm:text-sm sm:leading-5"
    >
      {disabledOption && (
        <option value="" disabled>
          {disabledOption}
        </option>
      )}
      {options &&
        options.map((o) => (
          <option value={o.value} key={o.value}>
            {o.text}
          </option>
        ))}
    </select>
  );
};

export default Select;

我这样使用它:

const countries = [
    { value: "NL", text: "Nederland " },
    { value: "BE", text: "Belgie " },
    { value: "DE", text: "Duitsland " },
    { value: "IT", text: "Italië " },
  ];

<Select
  id="country"
  options={countries}
  dispatchKey="SET_COUNTRY"
  selector="country"
  disabledOption="Kies een land"
/>

此下拉列表显示国家/地区。现在我已经硬编码了“IT”。但是,当加载组件时,当我在另一个字段中键入内容时,它会显示“NL”,它会突然显示“IT”。

我在做什么错,为什么“IT”没有立即显示?

标签: javascriptreactjs

解决方案


我想我可以解释你的Select组件的初始加载行为。

当您disabledOption作为道具传递时,默认值false设置为"Kies een land"现在。

因此,当执行以下命令时:-

  {disabledOption && (
    <option value="" disabled>
      {disabledOption}
    </option>
  )}

disabledOption不是空字符串是真实的并且不会短路。

所以渲染了以下元素。

<option value="" disabled>
          {disabledOption}
        </option>

因为它是disabled,所以显示的第一个条目countriesNL


推荐阅读