如何使用 Enter 提交语义反应搜索



我正在尝试设置我的搜索,所以当我单击输入时,它将开始搜索并重定向到搜索页面。我正在浏览文档,但不清楚如何设置它。如何设置按回车键开始搜索?我很难弄清楚这一点,尽管我认为这应该很简单。

class SearchBar extends Component {
constructor(props) {
super(props)
this.state = {query: '', results: [], isLoading: false}
}
componentWillMount() {
this.resetComponent()
}
resetComponent = () => this.setState({ isLoading: false, results: [], value: '' })
search(query) {
this.setState({ query });
axios
.get(`/api/search?query=${query}`)
.then(response => {
console.log(query);
this.setState({ results: response.data});
})
.catch(error => console.log(error));
}

handleSearchChange = (query) => {
this.search(query);
this.setState({ isLoading: true, query })
setTimeout(() =>
this.setState({
isLoading: false,
}) , 300)
}
handleResultSelect = (e, { result }) => this.setState({ query: result}  )
render () {
const resultRenderer = ({ title }) => <List content = {title}/>
return (
<Search
loading={this.state.isLoading}
onResultSelect={this.handleResultSelect}
onSearchChange={(event) => {this.handleSearchChange(event.target.value)}}
showNoResults={false}
query={this.props.query}
selectFirstResult = {true}
resultRenderer={resultRenderer}
results ={this.state.results}
{ ...this.props}  />
);
}
}

export default SearchBar

谢谢!

下面是如何执行此操作的最小示例。

import React from 'react'
import { Form, Input } from 'semantic-ui-react';
class FormExampleForm extends React.Component {
constructor(props) {
super(props);
this.state = {
query: ''
}
}
handleFormSubmit = () => {
console.log('search:', this.state.query);
}
handleInputChange = (e) => {
this.setState({
query: e.target.value
});
}
render() {
return (
<Form onSubmit={this.handleFormSubmit}>
<Form.Input  placeholder='Search...' value={this.state.query} onChange={this.handleInputChange} />
</Form>
)
}
}
export default FormExampleForm;

这是一个工作示例:https://stackblitz.com/edit/react-q5wv1c?file=Hello.js

修改语义 UI 中的搜索组件 反应源代码以实现 onKeyPress 处理程序

最新更新