如何在点击后关闭此搜索下拉列表?

时间:2017-03-30 03:00:35

标签: javascript reactjs

当我尝试在下拉列表中添加onClick =“{this.displayResults(false)}”时,它不会出现。 当我尝试将onClick =“{this.displayResults(false)}添加到搜索结果div时,它会与输入onChange事件冲突。 有关如何在用户点击搜索结果时关闭下拉列表的任何建议吗?

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import * as actions from '../actions';

class Search extends Component {

handleSearchTerm(term) {
    if (!term == "") {
        this.props.getSearchResults({term});
        this.displayResults(true);
    } else {
        this.displayResults(false);
    }
}

displayResults(display) {
    if (display === false) {
        $( ".search-results" ).css( "display", "none" );
    } else {
        $( ".search-results" ).css( "display", "block" );
    }
}


buildResultsList() {
    if (!this.props.searchResults) {
        return null;
    } else {
        const searchResultsList = this.props.searchResults.map(function (result) {
            return ([
                <div className="dropdown-divider"></div>,
                <Link to={`/project-spotlight/${result.uri}`} className="dropdown-item" id="search-result"> <li key={result.urlName}>{result.urlName}</li></Link>
            ]);
        });
        return searchResultsList;
    }
}


render() {
    console.log(this.props.searchResults);

    return (
        <div className="search-component">
            <form className="form-inline nav-search">
                <input
                    className="form-control mr-sm-2"
                    onChange={(e) => this.handleSearchTerm(e.target.value)}
                    id="navBarSearchForm"
                    aria-expanded="false"
                    aria-haspopup="true"
                    type="text"
                    placeholder="What Pod you looking for?"
                    autoComplete="off">
                </input>
            </form>
            <ul className="dropdown-menu search-results" >
                <h5 className="dropdown-header">-Pods-</h5>
                {this.buildResultsList()}
            </ul>
        </div>
    );
}


}

function mapStateToProps(state) {
return { searchResults: state.search.searchResult};
}

export default connect(mapStateToProps, actions)(Search);

1 个答案:

答案 0 :(得分:1)

event.preventDefault();添加到您的处理程序方法

  

如果调用此方法,则事件的默认操作不会   触发。

import React, { Component } from 'react';

export default class MyComponent extends Component {
  handleClick(event) {
    event.preventDefault();
    //...
  }

  render() {
    return (<button onClick={this.handleClick.bind(this)}>Submit</button>)
  }
}