简体   繁体   English

在有条件地呈现时,对onClick事件不会触发

[英]React onClick event not firing when it is conditionally rendered

I am building a searchDropdown component in React. 我正在React中构建一个searchDropdown组件。 I want to render dropdown only when search field is active. 我想仅在搜索字段处于活动状态时呈现下拉列表。 So I put a condition to render dropdown. 所以我提出了一个条件来渲染下拉列表。

But when the dropdown is rendered conditionally, onClick events inside dropdown are not triggering. 但是当有条件地呈现下拉列表时,下拉列表中的onClick事件不会触发。

My component is below. 我的组件如下。

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {List, ListItem} from 'material-ui/List';
import {Card} from 'material-ui/Card';
import Divider from 'material-ui/Divider';
import TextField from 'material-ui/TextField';
import resources from '../../resources/resources';
import cx from 'classnames';

import './SearchDropdown.scss';

class SearchDropdown extends Component {
  constructor(props) {
    super(props);
    this.cardContainerStyle = {
      'maxHeight': '300px',
      'overflow': 'scroll',
      'border': '1px solid rgb(158, 158,158)'
    };
    this.searchFieldUnderlineStyle = {
      'borderBottom': '1px solid #ccc'
    }
    this.state = {
      dropdownStyle: {}
    };
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.isActive && this.props.isActive !== nextProps.isActive) {
      this.shouldSetBounds = true;
    } else {
      this.shouldSetBounds = false;
    }
  }



  componentDidUpdate() {
    if(this.shouldSetBounds) {
      this._setDropdownBounds();
      this.shouldSetBounds = false;
    }
  }

  componentDidMount() {
    window.addEventListener('scroll',  this._handleScroll);
  }

  componentWillUnmount() {
    window.removeEventListener('scroll',  this._handleScroll);
  }

  _handleScroll = () => {
    if (this.props.isActive) {
      this._setDropdownBounds();
    }
  }

  _setDropdownBounds() {
    const dropdownContainerOffset = this.dropdownContainer.getBoundingClientRect();
    const containerTop = dropdownContainerOffset.top;
    const containerLeft = dropdownContainerOffset.left;
    const viewportHeight = window.innerHeight;
    const viewportWidth = window.innerWidth;
    const dropdownStyle = {
      top: dropdownContainerOffset.top + dropdownContainerOffset.height,
      left: dropdownContainerOffset.left
    };

    if (containerTop > viewportHeight/2) {
      dropdownStyle.top = 'auto';
      dropdownStyle.bottom = viewportHeight - containerTop;
    }
    this.setState({ dropdownStyle });
  }

  _renderDropdown() {
    const {onSelect, datalist = []} = this.props;

      return (
        <div className="search-dropdown-wrapper" style={this.state.dropdownStyle} onClick={(event) => {alert("Outer wrapper")}}>
          <Card containerStyle={this.cardContainerStyle}>
            <div>
            {"Sample Dropdown"}
            </div>
          </Card>
        </div>
      );
  }

  _renderSearchField() {
    const {value, handleSearch} =  this.props;

    return (
      <TextField
        value={value}
        onChange={handleSearch}
        fullWidth={true}
        hintText={resources.BRAND_SEARCH}
        underlineStyle={this.searchFieldUnderlineStyle}
      />
    );
  }

  render() {
    const {isActive, onBlur} = this.props;

    return (
      <div className="search-dropdown-container field-wrapper"
        ref={dropdownContainer => this.dropdownContainer = dropdownContainer}
        onBlur={onBlur}
        >
        {this._renderSearchField()}
        {isActive && this._renderDropdown()}
      </div>
    );
  }
}

SearchDropdown.propTypes = {
  isActive: React.PropTypes.bool.isRequired,
  value: React.PropTypes.string,
  datalist: React.PropTypes.array,
  handleSearch: React.PropTypes.func.isRequired,
  onSelect: React.PropTypes.func
}

export default SearchDropdown;

In above code, _renderDropdown will only execute when isActive is true . 在上面的代码中, _renderDropdown只会在isActivetrue时执行。 The compoenent is getting rendered perfectly with all styles when the search field is active. 当搜索字段处于活动状态时,组件将与所有样式完美呈现。 But when this component is rendered, the onClick event on the div with class search-dropdown-wrapper is not working. 但是当渲染此组件时,带有类search-dropdown-wrapperdiv上的onClick事件不起作用。

I'm not sure where I'm doing mistake. 我不确定我在哪里做错了。 Please let me know if there is any proper way to do this. 如果有任何正确的方法,请告诉我。 Thanks. 谢谢。

I finally made it work. 我终于成功了。

There is nothing wrong with the arrow function _renderDropdown used. 使用的箭头函数_renderDropdown没有任何问题。 The problem is with the onBlur event attached to the parent div with class search-dropdown-container of _renderDropdown . 问题在于使用_renderDropdownsearch-dropdown-container附加到父div的onBlur事件。 I have removed that onBlur event from there and added to search-dropdown-wrapper div. 我从那里删除了onBlur事件并添加到search-dropdown-wrapper div。 Then it started working fine. 然后它开始正常工作。

What I think is, The search-dropdown-wrapper position is fixed and so it will not be as part of search-dropdown-container technically. 我认为, search-dropdown-wrapper位置是fixed ,因此在技术上它不会作为search-dropdown-container一部分。 So click event happening on the search-dropdown-wrapper triggers onBlur event of search-dropdown-container first. 因此,首先在search-dropdown-wrapper触发onBlur事件的click search-dropdown-container上发生click事件。 So, the click event is not firing on search-dropdown-wrapper 因此, click事件不会在search-dropdown-wrapper上触发

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM