如何让用户能够按“Enter”进行搜索?

时间:2018-06-10 11:56:58

标签: javascript reactjs

我想通过单击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;

1 个答案:

答案 0 :(得分:3)

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(); 
    }
}