今天做一個收尋視窗,把輸入的值找到之後印到畫面上。
import React from 'react';
import Searchbar from './Searchbar';
class App extends React.Component {
render() {
return(
<div>
<Searchbar/>
</div>
);
}
}
export default App;
如圖:
首先定義一個input,然後再建構子也先定義資料,然後先抓到輸入值如下,
最後把輸入值存到state,等等用來比對資料。
import React from 'react';
class Searchbar extends React.Component {
constructor(props) {
super(props);
this.state = {
data:[
"Apples",
"Broccoli",
"Chicken",
"Duck",
"Eggs",
"Fish",
"Granola",
"Hash Browns"
],
search:''
};//內部自定義的變數
}
insert_text = (e) => { //利用本身事件(e)找到自己
this.setState({
search:e.target.value
})
console.log(e.target.value);//印出State.search狀態
}
render() {
return(
<div>
請輸入值:<input type="text" onChange={this.insert_text}/>
</div>
);
}
}
export default Searchbar;
如圖:
import React from 'react';
class Searchbar extends React.Component {
constructor(props) {
super(props);
this.state = {
data:[
"Apples",
"Broccoli",
"Chicken",
"Duck",
"Eggs",
"Fish",
"Granola",
"Hash Browns"
],
search:''
};//內部自定義的變數
}
insert_text = (e) => { //利用本身事件(e)找到自己
this.setState({
search:e.target.value
})
}
render() {
let updatedList = this.state.data.filter((item)=>{ //迭代後把值做比較
return item.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1 // indexOf 找到 = 1
}) //找到資料後存回 updatedList
let sort_data = updatedList.map((item,index,array)=>{ //把資料迭代後用成li標籤
return <li key={index}>{item}</li>
})
return(
<div>
請輸入值:<input type="text" onChange={this.insert_text}/>
{sort_data}
</div>
);
}
}
export default Searchbar;
如圖:
參考資料:
https://wcc723.github.io/javascript/2017/06/29/es6-native-array/
http://www.runoob.com/jsref/jsref-filter.html
https://www.ucamc.com/e-learning/javascript/276-react-js-search%E6%90%9C%E5%B0%8B%E5%8A%9F%E8%83%BD%E4%BD%BF%E7%94%A8%E9%81%8E%E6%BF%BE%E8%BF%B4%E5%9C%88filter.html
自己