React 外部点击组件封装

import React, { Component } from 'react';

import PropTypes from 'prop-types';

export default class OutsideClick extends Component {

  static propTypes = {

    onClickAway: PropTypes.func.isRequired,

    onClickAwayExceptions: PropTypes.array,

  };

  static defaultProps = {

    onClickAway: () => {},

    onClickAwayExceptions: [],

  };

  componentDidMount() {

    document.addEventListener('click', this.handle, true);

  }

  componentWillUnmount() {

    document.removeEventListener('click', this.handle, true);

  }

  handle = (e) => {

    const { onClickAway, onClickAwayExceptions } = this.props;

    let isExist = false;

    const el = this.container;

    onClickAwayExceptions

      .map((item) => {

        if (item instanceof window.jQuery) {

          return item;

        }

        if (typeof item === 'string' && window.jQuery) {

          return window.jQuery(item);

        }

        try {

          return ReactDom.findDOMNode(item);

        } catch (err) {

          return null;

        }

      })

      .forEach((item) => {

        if (item instanceof window.jQuery) {

          item.map((i, el) => {

            if (el.contains(e.target)) {

              isExist = true;

            }

          });

        } else if (item.contains(e.target)) {

          isExist = true;

        }

      });

    if (!el.contains(e.target) && !isExist) {

      onClickAway();

    }

  };

  render() {

    const { children, onClickAway, onClickAwayExceptions, ...props } = this.props;

    return (

        {...props}

        ref={(container) => {

          this.container = container;

        }}

      >

        {children}

    );

  }

}

你可能感兴趣的:(React 外部点击组件封装)