【问题标题】:How do I give users the ability to press “Enter” to search using react?如何让用户能够按“Enter”来使用 React 进行搜索?
【发布时间】:2018-11-19 20:38:57
【问题描述】:

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

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多