首页 > 解决方案 > 从选择元素中获取超过选项标签的值

问题描述

在我的反应应用程序中,我有一个select标签来选择一些选项。这些选项从 API 中获取并映射如下所示。

 <select
   id="numberbase__select"
   onChange={this.onSelectExistingNumberBase}>
            <option selected disabled hidden>Select a number base</option>
                  {this.props.tenantNumberBases.NumberBases.map((value, index) => {
                    return (
                        <option value={value.uuid}>{value.numberBaseName}</option>
                    );
                })}
 </select>

为了改变这个值,我使用了下面的辅助方法。

onSelectExistingNumberBase = (e) => {
    this.setState({
        existingNumberBase: e.target.value
    });
}

这样我就可以获得uuid映射数组值的 。但除了uuid,我也想得到numberBaseName。我尝试使用e.target.id. 但它没有用。我之所以能够得到uuid,是因为我已将其添加为option标签的值。我怎样才能得到更多的价值uuid呢?请帮忙。

标签: javascriptreactjs

解决方案


There might be few ways to achieve this. But I'll post here the solution that helped me.

First in select option, code like this.

<select
   onChange={this.onSelectExistingNumberBase}>
   <option selected disabled hidden>Select a number base</option>
   {this.props.tenantNumberBases.NumberBases.map((value, index) => {
         return (
             <option value={value.uuid} id={value.numberBaseName}>{value.numberBaseName}</option>
         );
   })}
</select>

Then in the onChange helper method I followed something like following.

onSelectExistingNumberBase = (e) => {
    this.setState({
        existingNumberBase: e.target.value,
        numberBaseName: e.target.options[e.target.selectedIndex].text,
    });
}

I was able to get options and then the value inside the option tag using selected index. I hope this will help someone who has the same problem.


推荐阅读