对于react-typeahead包的onKeyDown,我该如何使用它?

时间:2017-12-09 08:54:17

标签: reactjs onkeydown

我查看了Github上的代码,无法理解如何使用onKeyDown道具。目的是我得到的结果如下:

enter image description here

现在我希望onKeyDown突出显示1到1时的结果。然后我需要按enter来选择该选项。

有人能指出我正确的方向吗?

对不起,如果这是一个新手问题,但我似乎无法弄清楚如何使用此功能。请参阅下面的代码,了解我的应用的这一部分:



import React, {Component} from 'react';
import {Link} from 'react-router';
import LoginModal from '../homePage/LoginModal';
import {connect} from 'react-redux';
import {userLogout} from '../../actions/user.actions';
import $ from 'jquery';
import {Typeahead} from 'react-typeahead';
import {getPlaylists} from '../../actions/playlist.actions';
import {searchPlaylistData} from '../../helper';

class Nav extends Component {
  constructor(props) {
    super(props);
    this.state = {
      modal:false,
      toggleNav:false
    }

    this.toggleModal = this.toggleModal.bind(this);
    this.onToggleNav = this.onToggleNav.bind(this);
    this.onClickLogout = this.onClickLogout.bind(this);
    this.keyDown = this.keyDown.bind(this);
  }

  componentDidMount() {
    this.props.getPlaylists();
//     $('.navbar-nav').on('click', function(){
//       const collapse = $('#navbar').hasClass('collapse');
//       if (collapse === true){
//         // $('#navbar').removeClass('collapse');
//         this.setState({
//           toggleNav: false
//         })
//       }
//       else{
//         // $('#navbar').addClass('collapse');
//         this.setState({
//           toggleNav:true
//         })
//       }
//     });
}
  render () {
    return (
      <div>
      <nav className="navbar fixed-top navbar-static-top navbar-expand-lg navbar-light custom-bg">
        <a className="navbar-brand" href="#"><img className="logo" src="/images/logo.png"/></a>
        <button className="navbar-toggler" type="button" onClick={this.onToggleNav}>
          <span className="navbar-toggler-icon"></span>
        </button>
        <div id='navbar' className={this.state.toggleNav ? 'navbar-collapse' : 'collapse navbar-collapse'}>
          <ul className="nav navbar-nav mr-auto"></ul>
          <ul className="navbar-nav">
            <li className="nav-item active">
              <Link onClick={this.onToggleNav} className="nav-link" to={'/'}>Home</Link>
            </li>
            {this.props.userProfile.role === 'admin' ? 
            <li className="nav-item">
            <Link onClick={this.onToggleNav} className="nav-link" to ={'/addPlaylist'}>Playlists</Link>
          </li> :
            null }
            <li className="nav-item">
              <Link onClick={this.onToggleNav} className="nav-link" to ={'/contactUs'}>Contact</Link>
            </li>
            {}
          </ul>
          <div className="form-inline my-2 my-lg-0">
            {/* <input className="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"/> */}
            {console.log(this.props.playlists)}
            <Typeahead
              defaultValue=''
              options={this.props.playlists}
              filterOption='songTitle'
              displayOption={(option) => {
                return option.songTitle;
              }}
              onKeyDown={this.keyDown}
              customClasses={{
                input: "topcoat-text-input",
                results: "results-container"
              }} 
              className="form-control mr-sm-2"
              />

            {Object.keys(this.props.user).length !== 0 ? 
            <button onClick={this.onClickLogout} type="button" className="btn btn-primary my-2 my-sm-0">LogOut</button> : 
            <button onClick={this.toggleModal} type="button" className="btn btn-primary my-2 my-sm-0">Login</button>}
            
          </div>
        </div>
            <LoginModal show={this.state.modal} onClose={this.toggleModal} />
      </nav>
            </div>
    )
  }

   toggleModal () {
    this.setState({
      modal: !this.state.modal,
      toggleNav: false
    });
    
  }

  onToggleNav () {
    this.setState({
      toggleNav: !this.state.toggleNav
    })
  }

  onClickLogout () {
    this.props.userLogout();
    this.onToggleNav();
  }

  keyDown (event, event2) {
    console.log(event);
    console.log(event2)
  }
}

function mapStateToProps (state) {
  const searchablePlaylistData = searchPlaylistData(state.playlist.playlists);
  return {
    user: state.user.user,
    userProfile: state.user.userProfile,
    playlists: searchablePlaylistData

  }
}

function mapDispatchToProps (dispatch) {
  return {
    userLogout: () => {
      dispatch(userLogout());
    },
    getPlaylists: () => {
      dispatch(getPlaylists());
    }
  }
}
export default connect(mapStateToProps, mapDispatchToProps)(Nav);
&#13;
&#13;
&#13;

我试图看看是否有其他参数,但我认为它只是传入的事件。

1 个答案:

答案 0 :(得分:1)

我相信你对onKeyDown财产的目的感到困惑。

只要按下任何键,

onKeyDown就会被触发。听起来你想让用户点击键并循环显示当前选项,然后按 enter 选择一个。

值得庆幸的是,这是Typeahead的默认行为,我们只需要添加一些CSS来查看它的实际效果。

当用户插入值时,Typeahead将显示maxVisible个结果,我在下面的示例中使用4。如果用户然后单击键,它将选择结果中的第一个项目。单击将循环显示结果。然后单击 enter 将选择结果并将其插入输入中。如果没有合适的CSS,它将无法在行动中看到这一点。因此,您需要使用customClasses道具并为hover选项提供一种样式,以便明确选择结果。

不幸的是,由于需要使用react-typeahead npm模块,因此无法在Stackoverflow中创建工作示例,所以这里工作WebpackBin,这是代码:

<强>的index.html

<!doctype html>
<html>
  <head>
    <meta charset="utf-8"/>
    <link rel="stylesheet" type="text/css" href="app.css" />
  </head>
  <body>
    <div id="app"></div>
    <script src="main.js"></script>
  </body>
</html>

<强> main.js

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import {Typeahead} from 'react-typeahead';

class Nav extends Component {
  constructor(props) {
    super(props);
  }

  render () {
    return (
      <div className="container">
        <Typeahead
          options={[
            'Waylon Dalton',
            'Justine Henderson',
            'Abdullah Lang',
            'Marcus Cruz',
            'Thalia Cobb',
            'Mathias Little',
            'Eddie Randolph',
            'Angela Walker',
            'Lia Shelton',
            'Hadassah Hartman',
            'Joanna Shaffer',
            'Jonathon Sheppard'
          ]}
          maxVisible={4}
          defaultValue="o"
          customClasses={{
            input: "typeahead-text-input",
            results: "typeahead-list__container",
            listItem: "typeahead-list__item",
            hover: "typeahead-active",
          }}
        />
      </div>
    )
  }
}

ReactDOM.render(<Nav/>, document.getElementById("app"));

<强> app.css

html,
body {
  margin: 0;
  padding: 0;
  font-family: Arial;
  font-size: 18px;
}

.container {
  padding: 20px;
}

.typeahead-text-input {
  width: 100%;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border: 2px solid blue;
  font-size: 1em;
}

.typeahead-list__container {
  margin: 0;
  padding: 0;
}

.typeahead-list__item {
  list-style-type: none;
  padding: 5px 10px;
  margin: 0;
  font-size: 1em;
}

.typeahead-active {
  background: #eaeaea;
}