在React中为datalist选项创建onClick事件

时间:2017-05-10 17:18:14

标签: reactjs search datalist

我制作了一个Twitch API小部件,您可以在此处看到:https://twitch-react-drhectapus.herokuapp.com/

目前,只要您搜索某些内容,就会有一系列建议。我想这样做,以便当您点击其中一个datalist选项时,它将搜索该用户,而不必点击“搜索”。按钮。基本上与谷歌的搜索功能相同。

我该如何实施?

代码:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchUser, fetchSuggestions } from '../actions/index';

class SearchBar extends Component {
  constructor(props) {
    super(props);
    this.state = {
      term: ''
    };
    this.onInputChange = this.onInputChange.bind(this);
    this.onFormSubmit = this.onFormSubmit.bind(this);
  }

  onInputChange(event) {
    this.setState({
      term: event.target.value
    });
  setTimeout( this.props.fetchSuggestions(event.target.value), 300);
  }

  renderSuggestions(sug, i) {
    return (
      <option key={i} value={sug.display_name} />
    )
  }

  onFormSubmit(event) {
    event.preventDefault();
    this.props.fetchUser(this.state.term);
    this.setState({
      term: ''
    });
  }

  render() {
    const { error, suggestions } = this.props;
    return (

        <form
          className='input-group'
          onSubmit={this.onFormSubmit}>
          <input
            className='form-control'
            placeholder='Search for a Twitch user'
            value={this.state.term}
            onChange={this.onInputChange}
            list='suggestions' />
          <span className='input-group-btn'>
            <button className='btn btn-primary'>
              Search
            </button>
          </span>
          <datalist id='suggestions'>
            {suggestions.map(this.renderSuggestions)}
          </datalist>
        </form>


        // {/* {error && <div className='alert alert-danger'>{error}</div>} */}


    )
  }
}

function mapStateToProps({ error, suggestions }) {
  return { error, suggestions };
}

export default connect(mapStateToProps, { fetchUser, fetchSuggestions })(SearchBar);

0 个答案:

没有答案