javascript - Reactjs - 在下拉列表中获取映射数组的选定值
问题描述
我有一个下拉选择选项,它映射给定数组对象'template_titles'的数据。当前,该值设置为数组对象中的标题。我希望能够使用下拉列表中的选定值。我将如何获得该选定的值?
演示:https ://codesandbox.io/s/sleepy-tdd-i58lb?file=/src/App.jsx
const tester = () => {
const data = template_titles.find((e) => (e = 'I WANT THIS VALUE HERE'));
console.log(data);
setSubject(data.subject);
setText(data.text);
setCC(data.cc);
setBCC(data.bcc);
};
<div className='row wrapper'>
<label className='template'>Template</label>
<select
className='template-input'
id='template-select'
onChange={tester}
>
<option>---</option>
{template_titles.map((option) => (
<option
key={option.id}
value={option.title}
onChange={(e) => setTemplate(e.target.value)}
>
{option.title}
</option>
))}
</select>
</div>
解决方案
我建议使用 React Select 代替原生选择。看看https://react-select.com/home。它有一堆内置的附加功能,比如多选,甚至异步加载它的选项。它还允许用户输入以缩小它显示的选项,我认为这就是你所追求的。
它需要一组选项作为看起来像[{value: 'option-value', label: 'Option Value Shown To User'}]
.
它还需要一个onChange
which (对于单个选择)提供用户选择的选项,以便您的更改处理程序看起来像:
handleSelectChange(({ value }) => { /*whatever you want to do with the value*/ })
推荐阅读
- c++ - 控制到达非空函数的结尾 -wreturn-type
- asp.net-mvc - 通过 POST 发送多选
- reactjs - Heroku 在部署时给出应用程序错误
- java - 延迟一段时间后执行任务,如果遇到无限循环则停止
- azure-devops - Azure DevOps 管道从 UI 输入变量值
- preact - preact-cli 项目在添加 react-ga 时显示“无法解析 'react'”(别名问题)
- c++ - How can I check if Google services are blocked for my current user?
- javascript - How to stop the slider from resetting to the left side on mouse release (react-spring react-use-gesture)
- javascript - 如何申请 forEach();
- python - 我可以编写一个可以为 x 行重复图表的程序吗