使用反应选择但占位符未显示

Ale*_*ria 10 reactjs react-select

我已经完成了一些样式,正如您在这个沙箱上看到的那样,但我无法找出它的占位符文本。我不确定为什么会发生这种情况?

链接到 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>
    </>
  );
}
Run Code Online (Sandbox Code Playgroud)

Nea*_*arl 23

You are passing the wrong state to the value props of react-select

Change this line:

value={search}
Run Code Online (Sandbox Code Playgroud)

To:

value={search.country}
Run Code Online (Sandbox Code Playgroud)

Reason: search is a state object which is not falsy, placeholder will only be shown if you pass a falsy value (an empty string or undefined for example)

Live Demo

编辑 66867501/using-react-select-but-placeholder-is-not-showing

  • @AlexandriaSB 请参阅[此](/sf/answers/4183283051/)。您应该提供适当的接口供选择。尝试使用“{ label: d.name, value: d.name }”代替“{ label: d.name }” (2认同)