美文网首页
React 外部点击组件封装

React 外部点击组件封装

作者: 3__3剛睡醒 | 来源:发表于2018-08-28 17:08 被阅读0次

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 外部点击组件封装

      本文链接:https://www.haomeiwen.com/subject/vfeqwftx.html