【问题标题】:How can I close this search dropdown after a click?单击后如何关闭此搜索下拉菜单?
【发布时间】:2017-03-30 03:00:34
【问题描述】:

当我尝试将 onClick="{this.displayResults(false)}" 添加到下拉列表 li 时,它不会出现。 当我尝试将 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);

【问题讨论】:

    标签: javascript reactjs


    【解决方案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>)
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-17
      相关资源
      最近更新 更多