javascript - 我正在尝试在 React 中实现搜索过滤器,但它不起作用,你能帮帮我吗?
问题描述
我是 React 的新手,我正在尝试构建一个获取 API 的搜索过滤器,控制台没有给我任何错误,但是过滤器搜索栏不起作用,有人可以帮我吗?谢谢!
所以,我认为一切都应该没问题,因为在 chrome 控制台中,我没有收到任何错误,但 SearchBox.js 似乎不起作用
这是代码:
搜索框.js:
import React from 'react';
class SearchBox extends React.Component {
constructor(props) {
super(props)
this.state = {
suggestions: [],
text: '',
}
}
componentDidMount() {
fetch('https://api.scryfall.com/catalog/card-names')
.then(response => response.json())
.then(cards => this.setState({ suggestions: cards.data}))
}
onTextChanged = (event) => {
const { items } = this.props;
const value = event.target.value;
let suggestions = [];
if (value.length > 0) {
const regex = new RegExp(`^${value}`, '');
suggestions = Object.keys(items).sort().filter(word => regex.test(word))
}
this.setState(() => ({ suggestions, text: value }))
}
suggestionSelected (value) {
this.setState({
text: value,
suggestions: []
});
}
renderSuggestions () {
const { suggestions } = this.state;
if (suggestions.length === 0) {
return null;
}
return (
<ul>
{suggestions.map((item, index) => <li key={index} onClick={() => this.suggestionSelected(item)}>{item}</li>)}
</ul>
)
}
render () {
const { text } = this.state;
return (
<div>
<input value={text}
onChange={this.onTextChanged} type="text" />
{this.renderSuggestions()}
</div>
);
}
}
export default SearchBox;
应用程序.js:
import React from 'react';
import SearchBox from './components/SearchBox';
class App extends React.Component{
render() {
return(
<div>
<SearchBox items/>
</div>
)
}
};
export default App;
解决方案
您缺少函数绑定:
class SearchBox extends React.Component {
constructor(props) {
super(props)
this.state = {
suggestions: [],
text: '',
}
// == Binding ==
this.suggestionSelected = this.suggestionSelected.bind(this);
this.renderSuggestions = this.renderSuggestions.bind(this);
this.onTextChanged = this.onTextChanged.bind(this);
// == ======= ==
}
// [...]
}
推荐阅读
- javascript - 按 ID 将博文插入集合
- go - 不能在赋值中使用 (type string) 作为类型 func()
- jquery - 猫头鹰轮播“is-transitioned”类仅在初始化后从第二个图像添加,但在第一个图像的循环后工作
- kubernetes - 使用“kubectl”创建资源(cronjob)样板
- javascript - 如何在 googlemaps 上有多个具有不同信息窗口的标记
- javascript - 如何仅将加载添加到 vuejs 中的单击按钮?
- python - 当 gc 处理引用循环时,python 如何停止世界?
- vb.net - 使用内存流读取 Byte()-Array 中的图像时出现 6 个奇怪的零值
- node.js - 如何与 Node.js 中的本地模块共享依赖项?
- laravel - 使用集合 diff 函数时如何修复“stdClass 类的对象无法转换为字符串”