首页 > 解决方案 > 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> 

标签: javascripthtmlreactjs

解决方案


我建议使用 React Select 代替原生选择。看看https://react-select.com/home。它有一堆内置的附加功能,比如多选,甚至异步加载它的选项。它还允许用户输入以缩小它显示的选项,我认为这就是你所追求的。

它需要一组选项作为看起来像[{value: 'option-value', label: 'Option Value Shown To User'}].

它还需要一个onChangewhich (对于单个选择)提供用户选择的选项,以便您的更改处理程序看起来像:

handleSelectChange(({ value }) => { /*whatever you want to do with the value*/ })

推荐阅读