我正在使用React 16.13.0。我想构建一个简单的搜索组件,在用户键入内容时进行搜索。我已经创建了./src/components/Search.jsx
import React, { Component } from "react";
export default class Search extends Component {
constructor(props) {
super(props);
this.state = {
searchTerm: "",
setSearchTerm: "",
searchResults: [],
setSearchResults: []
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
console.log("value:" + event.target.value);
this.state.searchTerm = event.target.value;
fetch('/coops/?contains=' + encodeURIComponent(this.state.searchTerm),{
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
}).then(response => {
this.state.searchResults = response;
});
}
render() {
return (
<div className="searchForm">
<input
type="text"
placeholder="Search"
value={this.state.searchTerm}
onChange={this.handleChange}
/>
<ul>
{this.state.searchResults.map(item => (
<li>{item}</li>
))}
</ul>
</div>
);
}
}
渲染组件后,我遇到的问题是,在我键入内容时,搜索框中没有任何内容。我确实看到针对端点执行的请求,每个请求都包含我要键入的字母。我在输入时如何保持整个搜索字词在文本字段中显示的任何帮助都将受到赞赏。
替换为:
this.state.searchTerm = event.target.value;
带有此:
this.setState({searchTerm: event.target.value})
和searchResults:
this.setState({searchResults: response})