在反應我有一個對象,它看起來像反應
{
{name: 'Colombia', code: 'CO'},
{name: 'Comoros', code: 'KM'},
{name: 'Congo', code: 'CG'},
...}
我需要針對其用戶正在鍵入(我正在它從輸入字段)元件那裏搜索。由用戶編寫的每一個字母后,我需要把它與所有的名字比較,發現與部分
在反應我有一個對象,它看起來像反應
{
{name: 'Colombia', code: 'CO'},
{name: 'Comoros', code: 'KM'},
{name: 'Congo', code: 'CG'},
...}
我需要針對其用戶正在鍵入(我正在它從輸入字段)元件那裏搜索。由用戶編寫的每一個字母后,我需要把它與所有的名字比較,發現與部分
你想用filter()
和includes()
let a = [{
name: 'Congo',
code: 'CG'
},
{
name: 'France',
code: 'FR'
}
];
document.getElementById('foo').addEventListener('keyup', e => {
let val = e.target.value.toLowerCase();
let matches = a.filter(v => v.name.toLowerCase().includes(val));
console.log(matches);
});
<input id="foo">
我已經得到輸出文本了。 state.value你可以修改代碼,我可以在課堂上使用它嗎? –
所有名稱假設你不小心用大括號{}
,而不是括號[]
表示你的問題的數組,假設你可以使用ES6的功能,你可以使用Array.prototype.filter()
和String.prototype.includes()
:
// countries = your array
// Assuming you put the user input in a state variable called this.state.search = the user input string
var matchingCountries = countries.filter(element => element.name.includes(this.state.search));
如果你使用這個在組件的render
功能,以及地方使所得matchingCountries
陣列,該組件將反應性地更新爲this.state.search
已更新。
我已經採取了糾正你的數據類型的自由:
data = [{name: 'Congo', code: 'CG'}, ...]
,因爲您提供的版本將只拋出錯誤。
var data = [{name: 'Congo', code: 'CG'}];
...
handleKeyPress = (event) => {
var value = this.event.target.value.toLowerCase(),
matches = data.filter(function (item) {
return item.name.substring(0, value.length).toLowerCase() === value;
});
console.log(matches)
}
render: function(){
return(
<div>
<input type="text" onKeyPress={this.handleKeyPress} />
</div>
);
}
對不起,我的反應能力真的是分面值的,所以可能有更好的方式來訪問輸入的值,比event.target.value
。
不幸使用您的代碼我得到一個錯誤,你可以看看代碼? https://github.com/ArmenSan/reactSearch 錯誤是 錯誤./js/app.js 模塊構建失敗:SyntaxError:意外的令牌(35:17) > 35 | handleKeyPress =(event)=> { |^ 36 | var value = this.event.target.value.toLowerCase(), 37 |匹配=數據。過濾器(函數(item)){return item.name.substring(0,value.length).toLowerCase()=== value; –
爲什麼我們需要渲染函數? –
過濾基於搜索字符串的內容,像
var data = [{name: 'Comoros', code: 'KM'}, {name: 'Congo', code: 'CG'}, {name: 'Congo, The Democratic Republic of the', code: 'CD'}, {name: 'Cook Islands', code: 'CK'}, {name: 'Costa Rica', code: 'CR'}, {name: 'Cote D\'Ivoire', code: 'CI'}, {name: 'Croatia', code: 'HR'}, {name: 'Cuba', code: 'CU'}, {name: 'Cyprus', code: 'CY'}]
var search = 'om';
var filterData = data.filter(item => item.name.includes(search));
console.log(filterData);
這不是一個數組,它是一個嵌套對象。這也是無效的語法。 –
是的你是對的 –
那麼它是一個數組還是嵌套對象? – elmeister