簡體   English   中英

react-typeahead:獲取所選元素的ID

[英]react-typeahead: Get the id of the element selected

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

您可以對react-typeahead使用onOptionSelected回調來獲取選定的選項並使用它來查找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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM