使用 react-select 但未显示占位符

Using react-select but placeholder is not showing

我已经完成了一些您可以在这个沙盒上看到的样式,但是我无法弄清楚它的占位符文本。我不确定为什么会这样?

Link 到 CodeSandbox:

https://codesandbox.io/s/nifty-rgb-ro8to?file=/src/components/Countries.js

export default function Countries({ formValues, setFormValues }) {
  const [data, setData] = useState([]);
  const [search, setSearch] = useState({ country: "" });
  const { register, handleSubmit } = useForm();

  // Fetch Data From Api
  useEffect(() => {
    const fetchData = () => {
      fetch("https://restcountries.eu/rest/v2/all")
        .then((res) => res.json())
        .then((result) => setData(result))
        .catch((err) => console.log("error"));
    };
    fetchData();
  }, []);

  const options = data.map((d) => ({
    label: d.name
  }));

  function handleChange(item) {
    setSearch(item);
  }

  function onSubmit(values) {
    setFormValues({
      ...formValues,
      ...values,
      ...search
    });
    console.log({ ...formValues, ...values, ...search });
  }

  // styles for the select
  const customStyles = {
    option: (provided, state) => ({
      ...provided,
      borderBottom: "1px solid #dede",
      color: state.isSelected ? "#53e3a6" : "green",
      backgroundColor: "white",
      padding: 10
    }),
    control: (base, state) => ({
      ...base,
      color: state.isSelected ? "#53e3a6" : "green",
      border: "1px solid rgba(255, 255, 255, 0.4)",
      boxShadow: "none",
      margin: 20,
      "&:hover": {
        border: "1px solid rgba(255, 255, 255, 0.4)"
      }
    }),
    placeholder: (base) => ({
      ...base,
      // backgroundColor: "black",
      fontSize: "2em",
      color: "black",
      fontWeight: 400
    })
  };

  return (
    <>
      <form onSubmit={handleSubmit(onSubmit)} className="search">
        <Select
          type="text"
          defaultValue={""}
          placeholder={"Search Country...."}
          value={search.country}
          onChange={handleChange}
          name="Search"
          ref={register}
          options={options}
          styles={customStyles}
        />

        <div>
          <button type="Submit">Submit</button>
        </div>
      </form>
    </>
  );
}

您将错误的状态传递给 react-select

value 道具

更改此行:

value={search}

收件人:

value={search.country}

原因:search 是一个非虚假的状态对象,占位符只有在您传递虚假值(空字符串或 undefined 例如)时才会显示

现场演示