javascript - 提前 react : Get the id of the element selected

标签 javascript reactjs

我正在使用 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/

相关文章:

javascript - 未捕获( promise )TypeError : Cannot read property 'remove' of undefined

javascript - Angular 不会将字符串变量传递给 bool 表达式

javascript - 谁能解释一下为什么scrollspy和jquery在这里不起作用?

javascript - 以同步方式调用 Facebook Messenger API

javascript - 我一直在尝试创建一个 react 应用程序,但我不断收到此错误 : "npm ERR! cb() never called!"

javascript - form.submit 回调未被调用

reactjs - 访问 mapStateToProps 内的状态属性

javascript - 我应该如何将使用 Redux-Saga 进行长时间操作的 React 站点迁移到 React hooks?

javascript - 如何将 SweetAlert 关键字从 `swal` 更改为 'swal2'

javascript - 为什么这个CSS类条件在react js中不起作用?