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}

    );

  }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容