反应-映射两个字段的选项值?



我有以下示例数据:

# Json file
[
{"symbol": "ABC", "name": "Ace to The Base Camp", "country": "United States", "industry": "Electrical Products"}, 
{"symbol": "BAC", "name": "BLAST OFF", "country": "United States", "industry": "Electrical Products"}
]

目前我使用map创建option,并让用户仅基于symbol搜索和选择正确的symbol

使用这个:

<input name="ticker" id="ticker" list="stockSelection" onChange={this.onChange} value={ticker} className="form-control text-center" />
<datalist id="stockSelection">
{this.state.country === "United States of America"
? USDATA.map(({symbol}) => <option value={symbol}/>)
: INDIADATA.map(({symbol}) => <option value={symbol}/>)}
</datalist>

我想在搜索字段中显示name(来自json文件),使其也可搜索。

我的意思的例子:

当前用户类型"下拉列表显示ABC为符号。没有显示ABC的名字,例如"Ace to the Base camp"。我想要名字显示和搜索。onSelect我只想要这个符号

试着弄清楚,但失败了。

您可以像提取symbol一样提取name。这样,名称"Ace to The Base Camp"将显示给用户,值ABC将作为选项标签的值返回。

通常我这样做:

<datalist id="stockSelection">
{this.state.country === "United States of America"
? USDATA.map(({symbol, name}) => <option key={symbol} value={symbol}>{name}</option>)
: INDIADATA.map(({symbol, name}) => <option key={symbol} value={symbol}>{name}</option>)}
</datalist>

为问题的第二部分:

当你搜索时,你基本上过滤了结果。所以你可以这样做:

const [input, setInput] = useState();
// search input handler 
const handleChange = (e) => {
setInput(e.target.value)
};
// in your component
<select>
{myList.filter(item => input.indexOf(item.symbol) >= 0 || input.indexOf(item.name) >= 0)
.map(item => <option key={item.symbol} value={item.symbol}>{item.name}</option>)}
</select>

最新更新