我正在我的 nextjs 项目中使用从下一个 ui 中选择 我已经成功实现了它,并且工作正常,但问题是我无法从中获取所选值,我想将所选值存储在 setState 中,并且我已尝试按照文档建议使用 onchange 但我正在获取索引而不是字符串本身
这是我的代码
"use client";
import React, { useState } from "react";
import { Select, SelectItem } from "@nextui-org/select";
const ServiceInfoContainer = () => {
const [service, setService] = useState("");
const categories = ["Beginner (0-1 year)", "Intermediate (2-3 years)", "Experienced (4-5 years)", "Expert (6+ years)"];
const handleChange = (e)=> setService(e.target.value)
<Select onChange={handleChange} label="Select years of experience">
{categories.map((categ, index) => (
<SelectItem key={index} value={categ}>
{categ}
</SelectItem>
))}
</Select>
}
当我控制台记录服务时,我得到 1 2 3 对应于所选选项,就像它给我索引而不是字符串值
我想获取选定的值而不是我当前获取的索引
你的问题是关键,只需使用预期的值作为键,在这个例子中,类别是值,所以使用它作为键。
"use client";
import React, { useState } from "react";
import { Select, SelectSection, SelectItem } from "@nextui-org/select";
const ServiceInfoContainer: React.FC = () => {
const [service, setService] = useState<string>("");
const categories: string[] = [
"Beginner (0-1 year)",
"Intermediate (2-3 years)",
"Experienced (4-5 years)",
"Expert (6+ years)",
];
const handleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
setService(e.target.value);
};
return (
<>
Service: {service}
<Select onChange={handleChange} label="Select years of experience">
{categories.map((categ) => (
<SelectItem key={categ} value={categ}>
{categ}
</SelectItem>
))}
</Select>
</>
);
};
export default ServiceInfoContainer;