
先在state里模拟一个数据,用于搜索。
然后写一个input框,添加onChange监听事件,当我们输入内容的时候,会自动去匹配数据,如果包含一样的字就显示出来。

然后要做的是在input框输入值的同时,遍历listDog数组,看有没有输入的那个值。
如果有的话,显示出包含那个值的所有元素,如果没有则返回一个空数组。默认刚打开页面是空的。
可以先封装一个回调,注意在回调里的this的指向问题。可以写一个button来观察this


知识点-改变this指向的三种方法
- 方式1:把方法变成剪头函数 名字=()=>{}
- 方法2:在事件中 调用方法的时候.bind(this) 好处是可以传值 onClick={ this.xxx回调函数.bind(this) }
- 方法3:在构造函数中直接绑定this

继续写遍历数组的逻辑:

import React, { Component } from 'react';
class Search extends Component {
constructor(props) {
super(props);
//在最开始的时候 把方法绑定给this
this.filterDog = this.filterDog.bind(this);
//方式1 把方法变成箭头函数
//方式2 事件中 调用方法的时候 .bind(this) 可以传值
//方式3 在构造函数中直接绑定this
}
state = {
inputValue: '',
listDog: ['哈士奇', '哈士奇短毛', '哈士奇长毛',
'雪纳瑞', '雪纳瑞白色', '雪纳瑞黑色',
'金毛', '狗阿拉斯加',
'狗拉布拉多', '拉布拉多卡其色']
};
//改变this指向 另一个写法
//初始的时候绑定一下this 在构造函数constructor里写
filterDog(key) {
console.log(this)
//遍历this.state.listDog
return !key?[]:this.state.listDog.filter(item => item.includes(key));
}
render() {
let {inputValue} = this.state;
return (
<div>
<input type="text" onChange={(ev) => {
this.setState({
inputValue: ev.target.value
})
}} />
<button onClick={this.filterDog}>看看this</button>
<ul>
{
this.filterDog(inputValue).map(item=>(<li key={item}>
<h3>{item}</h3>
</li>))
}
</ul>
</div>
);
}
}
export default Search;
这篇博客记录了使用React实现类似百度搜索的实时数据筛选功能。通过在state中模拟数据,结合onChange事件监听input输入,动态匹配并显示包含输入字符的元素。文中详细介绍了在遍历过程中处理this指向问题的三种方法,并提供了示例代码。
403

被折叠的 条评论
为什么被折叠?



