[![npm version](https://img.shields.io/npm/v/react-onclickoutside.svg)](https://www.npmjs.com/package/react-onclickoutside)
[![Build Status](https://travis-ci.org/Pomax/react-onclickoutside.svg?branch=master)](https://travis-ci.org/Pomax/react-onclickoutside)
[![npm](https://img.shields.io/npm/dm/react-onclickoutside.svg)](https://www.npmjs.com/package/react-onclickoutside)
# :warning: Open source is free, but developer time isn't :warning:
**This package needs your support to stay maintained.** If you work for an organization
whose website is better off using react-onclickoutside than rolling its own code
solution, please consider talking to your manager to help
[fund this project](https://www.paypal.com/donate/?cmd=_s-xclick&hosted_button_id=QPRDLNGDANJSW).
Open Source is free to use, but certainly not free to develop. If you have the
means to reward those whose work you rely on, please consider doing so.
# An onClickOutside wrapper for React components
This is a React Higher Order Component (HOC) that you can use with your own
React components if you want to have them listen for clicks that occur somewhere
in the document, outside of the element itself (for instance, if you need to
hide a menu when people click anywhere else on your page).
Note that this HOC relies on the `.classList` property, which is supported by
all modern browsers, but not by deprecated and obsolete browsers like IE (noting
that Microsoft Edge is not Microsoft Internet Explorer. Edge does not have any
problems with the `classList` property for SVG elements). If your code relies on
classList in any way, you want to use a polyfill like
[dom4](https://github.com/WebReflection/dom4).
This HOC supports stateless components as of v5.7.0, and switched to using
transpiled es6 classes rather than `createClass` as of v6.
## Sections covered in this README
* [Installation](#installation)
* [Usage:](#usage)
* [Functional Component with UseState Hook](#functional-component-with-usestate-hook)
* [ES6 Class Component](#es6-class-component)
* [CommonJS Require](#commonjs-require)
* [Ensuring there's a click handler](#ensuring-there-is-a-click-handler)
* [Regulate which events to listen for](#regulate-which-events-to-listen-for)
* [Regulate whether or not to listen for outside clicks](#regulate-whether-or-not-to-listen-for-outside-clicks)
* [Regulate whether or not to listen to scrollbar clicks](#regulate-whether-or-not-to-listen-to-scrollbar-clicks)
* [Regulating `evt.preventDefault()` and `evt.stopPropagation()`](#regulating-evtpreventdefault-and-evtstoppropagation)
* [Marking elements as "skip over this one" during the event loop](#marking-elements-as-skip-over-this-one-during-the-event-loop)
* [Older React code: "What happened to the Mixin??"](#older-react-code-what-happened-to-the-mixin)
* [But how can I access my component? It has an API that I rely on!](#but-how-can-i-access-my-component-it-has-an-api-that-i-rely-on)
* [Which version do I need for which version of React?](#which-version-do-i-need-for-which-version-of-react)
* [Support-wise, only the latest version will receive updates and bug fixes.](#support-wise-only-the-latest-version-will-receive-updates-and-bug-fixes)
* [IE does not support classList for SVG elements!](#ie-does-not-support-classlist-for-svg-elements)
* [I can't find what I need in the README](#i-cant-find-what-i-need-in-the-readme)
## Installation
Use `npm`:
```
$> npm install react-onclickoutside --save
```
(or `--save-dev` depending on your needs). You then use it in your components
as:
## Usage
### Functional Component with UseState Hook
This HoC does not support functional components, as it relies on class properties and component instances. However, you almost certainly don't need this HoC in modern (React 16+) functional component code, as a simple function will do the trick just fine. E.g.:
```js
function listenForOutsideClicks(listening, setListening, menuRef, setIsOpen) {
return () => {
if (listening) return;
if (!menuRef.current) return;
setListening(true);
[`click`, `touchstart`].forEach((type) => {
document.addEventListener(`click`, (evt) => {
if (menuRef.current.contains(evt.target)) return;
setIsOpen(false);
});
});
}
}
```
Used in a functional component as:
```js
import React, { useEffect, useState, useRef } from "react";
import listenForOutsideClicks from "./somewhere";
const Menu = () => {
const menuRef = useRef(null);
const [listening, setListening] = useState(false);
const [isOpen, setIsOpen] = useState(false);
const toggle = () => setIsOpen(!isOpen);
useEffect(listenForOutsideClick(
listening,
setListening,
menuRef,
setIsOpen,
));
return (
<div ref={menuRef} className={isOpen ? "open" : "hidden"}>
<h1 onClick={toggle}>...</h1>
<ul>...</ul>
</div>
);
};
export default Menu;
```
Example: https://codesandbox.io/s/trusting-dubinsky-k3mve
### ES6 Class Component
```js
import React, { Component } from "react";
import onClickOutside from "react-onclickoutside";
class MyComponent extends Component {
handleClickOutside = evt => {
// ..handling code goes here...
};
}
export default onClickOutside(MyComponent);
```
### CommonJS Require
```js
// .default is needed because library is bundled as ES6 module
var onClickOutside = require("react-onclickoutside").default;
var createReactClass = require("create-react-class");
// create a new component, wrapped by this onclickoutside HOC:
var MyComponent = onClickOutside(
createReactClass({
// ...,
handleClickOutside: function(evt) {
// ...handling code goes here...
}
// ...
})
);
```
### Ensuring there is a click handler
Note that if you try to wrap a React component class without a
`handleClickOutside(evt)` handler like this, the HOC will throw an error. In
order to use a custom event handler, you can specify the function to be used by
the HOC as second parameter (this can be useful in environments like TypeScript,
where the fact that the wrapped component does not implement the handler can be
flagged at compile-time):
```js
// load the HOC:
import React, { Component } from "react";
import onClickOutside from "react-onclickoutside";
// create a new component, wrapped below by onClickOutside HOC:
class MyComponent extends Component {
// ...
myClickOutsideHandler(evt) {
// ...handling code goes here...
}
// ...
}
var clickOutsideConfig = {
handleClickOutside: function(instance) {
return instance.myClickOutsideHandler;
}
};
var EnhancedComponent = onClickOutside(MyComponent, clickOutsideConfig);
```
Note that if you try to wrap a React component with a custom handler that the
component does not implement, the HOC will throw an error at run-time.
## Regulate which events to listen for
By default, "outside clicks" are based on both `mousedown` and `touchstart`
events; if that is what you need, then you do not need to specify anything
special. However, if you need different events, you can specify these using the
`eventTypes` property. If you just need one event, you can pass in the event
name as plain string:
```js
<MyComponent eventTypes="click" ... />
```
For multiple events, you can pass in the array of event names you need to listen
for:
```js
<MyComponent eventTypes={["click", "touchend"]} ... />
```
## Regulate whether or not to listen for outside clicks
Wrapped components have two functions that can be used to explicitly listen for,
or do nothing with, outside clicks
* `enableOnClickOutside()` - Enables outside click listening by setting up the
event listening bindings.
* `disableOnClickOutside()` - Disables outside click listening by explicitly
removing the event listening bindings.
In addition, you can create a component that uses this HOC such that it has the
code set up and ready to go, but not listening for outside click events until
you explicitly issue its `enableOnClickOutside()`, by pa
React组件的onClickOutside包装器_JavaScript_HTML_下载.zip
版权申诉
123 浏览量
2023-04-21
11:02:43
上传
评论
收藏 154KB ZIP 举报
快撑死的鱼
- 粉丝: 1w+
- 资源: 9154
最新资源
- 基于Pytorch训练CIRAR10上分类算法.zip
- Pytorch-pytorch深度学习教程之Tensorboard.zip
- 基于C++和Python开发yolov8-face作为人脸检测器dlib作为人脸识别器的人脸考勤系统源码+项目说明.zip
- Pytorch-pytorch深度学习教程之变分自动编码器.zip
- Pytorch-pytorch深度学习教程之神经风格迁移.zip
- Pytorch-pytorch深度学习教程之深度残差网络.zip
- Pytorch-pytorch深度学习教程之循环神经网络.zip
- Pytorch-pytorch深度学习教程之逻辑回归.zip
- Pytorch-pytorch深度学习教程之双向循环网络.zip
- Pytorch-pytorch深度学习教程之卷积神经网络.zip
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈