Javascript 如何获取React Select选项的值?
如何从unitOptions数组和React Select组件中获取值? 我想把它传递到一个Express文件,所以它被用作一个OpenWeather url来显示天气信息。 提前谢谢Javascript 如何获取React Select选项的值?,javascript,reactjs,react-select,Javascript,Reactjs,React Select,如何从unitOptions数组和React Select组件中获取值? 我想把它传递到一个Express文件,所以它被用作一个OpenWeather url来显示天气信息。 提前谢谢 import React, {useState} from 'react' import Select from 'react-select' const unitOptions = [ {value: 'metric', label: 'Celcius'}, {value: 'imperial', l
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>
import React,{useState}来自“React”
从“反应选择”导入选择
常量单位选项=[
{值:'metric',标签:'Celcius'},
{值:'imperial',标签:'Fahrenheit'}
];
函数仪表板(){
const[units,setUnits]=useState(“”);
const[city,setCity]=useState(“”);
函数selectUnits(){
常量单位=document.getElementById(“unitSelect”).value;
控制台日志(单位);
}
功能选择城市(事件){
const cityName=event.target.value;
const targetName=event.target.name;
}
返回(
onChange
应向您传递一个包含select值的参数
function selectUnits(input) {
console.log(input.value);
}
使用prop
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>
);
}
import React,{useState}来自“React”;
从“反应选择”导入选择;
导出带有回调函数的默认函数(){
const[myOption,setMyOption]=useState(“默认文本”);
常量handleInput=(newValue)=>{
setMyOption(newValue.value);
返回新值;
};
返回(
{myOption}
);
}
在selectUnit()
函数中输入一个参数,该参数是所选选项