使用fontawesome时onClick不会触发

时间:2016-08-24 20:33:07

标签: javascript reactjs onclick font-awesome

我有一个反应组件SearchField,它是输入的包装器。我试图获得一个fontawesome(x)来点击时清除输入框,但所有尝试让onClick开火都失败了。

如果我剪切并粘贴到父div,则onClick会触发。 如果我将元素更改为元素,它仍然会失败。 我曾尝试使用chrome工具手动将其定位在输入之外,但仍无法触发。 我试过增加宽度和高度,这也失败了。

注意:_base是React.Component

的包装器

以下是代码:

import React, { PropTypes }    from 'react';
import _Base                   from '_Base';
import _                       from 'underscore';
import classNames              from 'classnames';

export default class SearchField extends _Base {
  static defaultProps = {
    name:          null,
    placeholder:   null,
    onSearch:      null,
    searchOnEnter: true,
    liveSearch:    false,
    delay:         250
  };

  static propTypes = {
    name:          PropTypes.string.isRequired,
    placeholder:   PropTypes.string,
    onSearch:      PropTypes.func,
    searchOnEnter: PropTypes.bool,
    liveSearch:    PropTypes.bool,
    delay:         PropTypes.number,
  };

  state = {
    __value: null
  };

  constructor(props) {
    super(props);
    let me = this;
    if(props.delay > 0){
      me.onKeyDown = _.debounce(me._onKeyDown, props.delay);
    } else {
      me.onKeyDown = me._onKeyDown;
    }
  }

  __onKeyDown(event) {
    event.persist();
    this.onKeyDown(event);
  }

  _onKeyDown(e) {
    var me = this
      , props = me.props
      , val   = me.refs.search.value
      ;

    me.setState({ __value: val });

    if(props.liveSearch ||
      (props.searchOnEnter && e.key === "Enter")) {
      me._onSearch(val);
      return;
    }
  }

  _clearSearch() {
    var me = this;

    me.refs.search.value = "";
    me.setState({ __value: "" });

    me._onSearch("");
  }

  _onSearch(val) {
    var me = this
      , props = me.props
      ;

    if(props.onSearch) {
      props.onSearch({ name: props.name, value: val });
    }
  }

  render() {

    return (
      <div className={classNames("search-field form-group has-feedback", this.props.className)}>
        <input
          ref            = {"search"}
          className      = "form-control"
          type           = "search"
          autoCapitalize = "none"
          autoComplete   = "off"
          autoCorrect    = "on"
          autoSave       = "true"
          autofocus      = "false"
          spellCheck     = "false"
          name           = {this.props.name}
          placeholder    = {this.props.placeholder}
          onKeyDown      = {this.__onKeyDown}
        />
        <i className="fa fa-times-circle cursor-pointer form-control-feedback"
           onClick = {this._clearSearch}
           title   = "Clear Search"
        />

      </div>
    );
  }
}

2 个答案:

答案 0 :(得分:1)

相同的代码对我来说很好,请确保您没有任何元素覆盖在顶部,并且没有css禁用鼠标事件,如pointer-events: none

答案 1 :(得分:-1)

发生这种情况的原因是因为_clearSearch函数中没有正确的this。你需要明确地绑定它。

在构造函数中,执行

this._clearSearch = this._clearSearch.bind(this);

它应该有用。如果您仍然面临这个问题,请告诉我们。