[英]How do I give users the ability to press “Enter” to search using react?
我想通过单击ENTER键来添加搜索功能。 如何在代码中添加它? 这是来自Codecademy项目
import React, { Component } from 'react';
import './SearchBar.css';
class SearchBar extends Component {
constructor(props) {
super(props);
this.search = this.search.bind(this);
this.handleTermChange = this.handleTermChange.bind(this);
}
handleTermChange(event) {
const newTerm = event.target.value;
this.setState = ({ term: newTerm});
}
search() {
this.props.onSearch(this.state.term);
}
render() {
return(
<div className="SearchBar">
<input placeholder="Enter A Song, Album, or Artist" onChange = {this.handleTermChange}/>
<a onClick ={this.search}>SEARCH</a>
</div>
)}
}
export default SearchBar;
React为输入实现onKeyUp
方法
<input placeholder="Enter A Song, Album, or Artist" onChange={this.handleTermChange} onKeyUp={this.handleKeyPress.bind(this)}/>
并在您的组件中创建一个方法:
handleKeyPress(e) {
if (e.key === 'Enter') {
this.search();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.