我正在使用 react-typeahead , 我试图在选择一个选项或提交表单时存储和获取元素的 ID
到目前为止我有这个:
data = [{ id: 1, name: "something", id: 2, name: "else"}];
我使用这样的映射来仅获取名称,因为 Typeahead 选项默认需要一个字符串数组,所以我们在这里丢失了 id。
map(function (item) {return item.name;})
<Typeahead options={categories} placeholder="Categories" />
我的问题是如何在提交表单或选择选项时保留和获取类别的 ID。
这将是这样的形式:
<form method="get" action="/" className="form-inline" >
<Typeahead options={categories} onOptionSelected={this._handleOnOptionSelected} placeholder={text} maxVisible={5} />
<Link to="/search" onClick={this._handleOnClick} className="btn btn-wa-primary">Search</Link>
</form>
最佳答案
您可以使用 onOptionSelected
react-typeahead 的回调以获取所选选项并使用它来查找 id:
/* somewhere in your top component */
handleOptionSelected: function(option) {
// find the id from the data array
var id = data.find(function(d) {
return d.name === option;
});
// ... now you have the id
},
/* somewhere in the render() method of your top component */
<Typeahead options={categories}
placeholder="Categories"
onOptionSelected={this.handleOptionSelected} />
由于您没有在任何地方显示表单,因此我无法解决“表单提交”问题。
注意:您可以通过使用映射而不是数组来查找 ID 来优化这一点。像这样的东西:
var map = {
"something": 1,
"else": 2
};
其中,id
将是 map[option]
。
关于javascript - 提前 react : Get the id of the element selected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37740929/