简体   繁体   English

检测组件外部的点击反应不访问dom

[英]Detect click outside a component react way NOT dom access

I am implementing a crop feature with React. 我正在用React实现裁剪功能。 When the user right clicks, a context menu appears. 当用户右键单击时,将显示一个上下文菜单。 In the context menu, a user can select crop item. 在上下文菜单中,用户可以选择作物项目。 When a user selects crop, cropping gets activated. 当用户选择裁剪时,裁剪将被激活。 Now, I want to close the cropping state when the user clicks outside of that division. 现在,我想在用户单击该分区以外的区域时关闭裁剪状态。 How do I have to do react way without DOM manipulation? 没有DOM操作,我该怎么做? Or should I have to use DOM manipulations such as add EventListener & removeListener ? 还是我必须使用DOM操作(例如add EventListener & removeListener What are the cons of using DOM access here? 在这里使用DOM访问有什么弊端? Please let me know this thoroughly since this is going to be implemented in many of the features I am going to develop. 请让我彻底知道这一点,因为这将在我将要开发的许多功能中实现。 For example, the context menu I was talking about, or the dropdown menu. 例如,我正在谈论的上下文菜单或下拉菜单。

Here is an example for the reference - Sandbox . 这是参考-Sandbox的示例。 Now, when the user clicks outside of ReactCrop component, I want to close the crop through react way. 现在,当用户在ReactCrop组件之外单击时,我想通过react方式关闭作物。

I don't want to go ahead with document.addEventListener or removeListener . 我不想继续进行document.addEventListener or removeListener

If you really, really don't want to attach dom events to your components, you can add a 'dismisser' component behind the Crop component and handle the reset there. 如果确实不希望将dom事件附加到组件,则可以在Crop组件后面添加一个“ dismisser”组件,并在那里进行重置。

const Dismisser = ({ onClick }) => <div onClick={onClick} style={{
  position: 'fixed',
  top: 0, left: 0, right: 0, bottom: 0,
  zIndex: 100,
}} />

In your component: 在您的组件中:

{src && (
  <React.Fragment>
  <div style={{position: 'relative', zIndex: 200}}>
    <ReactCrop
      src={src}
      crop={crop}
      ...
    />
  </div>
  <Dismisser onClick={this.resetCrop} />
  </React.Fragment>
)}

Codesandbox 密码箱

I'd say that's a bit more 'React-y' since the responsiblity of reseting the crop is delegated to another component. 我想说的是更多的“ React-y”,因为重置作物的责任委托给了另一个组件。 However it'll give you trouble when your Crop component is behind other Dom element, z-index wise. 但是,如果您的Crop组件位于其他Dom元素(z-index明智)之后,则会给您带来麻烦。 You can get over it by using portal, but it'll start to get complex. 您可以使用门户网站克服它,但是它将变得越来越复杂。

I think attaching DOM event is a valid solution here (as long as you remember to remove them). 我认为在这里附加DOM事件是一个有效的解决方案(只要您记得将其删除即可)。 It's simpler, plus it's not like you're directly manipulating a dom node using data outside of React's flow, which most of the time is the real bad case. 它更简单,而且不代表您使用React流之外的数据直接操纵dom节点,而在大多数情况下,这是最糟糕的情况。

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

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