如何获取 React-Select 选项的值?

How do I get the value of the React-Select option?

如何从 React-Select 组件的 unitOptions 数组中获取值? 我想将它传递给一个 Express 文件,所以它被用作 OpenWeather url 来显示天气信息。 提前致谢。

import React, {useState} from 'react'
import Select from 'react-select'

const unitOptions = [
  {value: 'metric', label: 'Celcius'},
  {value: 'imperial', label: 'Fahrenheit'}
];

function Dashboard() {
  const [units, setUnits] = useState("");
  const [city, setCity] = useState("");

function selectUnits() {

    const units = document.getElementById("unitSelect").value;
    console.log(units);
}

function selectCity(event) {

    const cityName = event.target.value;
    const targetName = event.target.name;
}


return(

    <div>
      <form className="inputArea">
        <Select
          id="unitSelect"
          options={unitOptions}
          className="unitSelect"
          placeholder="Units"
          onChange={selectUnits}
        />
    </div>

onChange 应该向您传递一个包含 select.

值的参数
function selectUnits(input) {
  console.log(input.value);
}

使用道具 onChange 你可以传入一个接收事件值的函数(回调),这样你就可以将它传递给状态:

import React, { useState } from "react";

import Select from "react-select";

export default function WithCallbacks() {
    const [myOption, setMyOption] = useState("Default text");

    const handleInput = (newValue) => {
        setMyOption(newValue.value);
        return newValue;
    };

    return (
        <div>
             <p>{myOption}</p>
             <Select
                 options={[
                     {
                         label: "no label",
                         value: "novalue"
                     }
                 ]}
                 onChange={handleInput}
             />
         </div>
     );
 }