简体   繁体   English

如何检测React功能组件之外的点击

[英]How to detect click outside of the React functional component

I want to detect click outside of the React functional component. 我想检测React 功能组件之外的点击。

Then I found the following article and implemented code accordingly. 然后,我找到了以下文章,并相应地实现了代码。

Detect click outside React component 检测React组件外部的点击

But my code does not work. 但是我的代码不起作用。 I understand the cause, however don't know solution. 我了解原因,但是不知道解决方法。

import React from 'react';
import Foo from 'foo'; // <- Functional component in the node_modules

export default class extends React.PureComponent {
  private readonly refRoot = React.createRef();
  public componentDidMount() {
    document.addEventListener('click', this.clickOutside);
  }
  public componentWillUnmount() {
    document.removeEventListener('click', this.clickOutside);
  }
  private clickOutside(ev: MouseEvent) {
    if (refRoot.current.contains(ev.target)) {
      console.log('clicked outside.');
    }
  }
  public render(){
    return (
      <Foo ref={this.refRoot}> // <- Doubt.
        ...
      </Foo>
    );
  }
}

Because cannot use the ref attribute on function component . 因为不能在函数组件上使用ref属性

Maybe able to solve it by wrapping it with a div element, but I want to avoid complicating the stratum of the DOM any more when rendered to HTML. 也许可以通过使用div元素将其包装来解决,但我想避免在呈现为HTML时使DOM的层次更加复杂。

What do you have any ideas? 您有什么想法?

If you want to use ref inside of functional component, then rather than passing it from parent, you can use React hooks API. 如果您想在功能组件内部使用ref,那么可以使用React hooks API而不是从parent传递它。 https://reactjs.org/docs/hooks-reference.html#useref https://reactjs.org/docs/hooks-reference.html#useref

Please check the above ^^ 请检查上面的^^

The idea to create a ref on the DOM element rendered inside of Foo which you can do by passing it as a props which can be used in Foo 在Foo内部呈现的DOM元素上创建ref的想法,您可以通过将其作为道具传递给Foo来使用。

  <Foo innerRef={this.refRoot}> 
    ...
  </Foo>

Inside Foo: 内部Foo:

const Foo = (props) => {
   return <div ref={props.innerRef}>{/* data here */}</div>
}

or you could use React.forwardRef to forward Foos ref to its children 或者您可以使用React.forwardRef将Foos ref转发给它的子级

const Foo = React.forwardRef(props, ref) => {
   return <div ref={ref}>{/* data here */}</div>
}

Parent

public render(){
    return (
      <Foo ref={this.refRoot}> // <- Doubt.
        ...
      </Foo>
    );
  }

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

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