简体   繁体   English

React钩子onClick仅针对父级触发(模态)

[英]React hooks onClick fire only for parent (modal)

I have a modal window and i want it to hide if user clicked on modal itself(black background), but click is trigerring by clildrens to. 我有一个模态窗口,如果用户单击模态本身(黑色背景),我希望将其隐藏,但是单击会导致用户点击。 Here is the example: 这是示例:

import React, { useState, useEffect } from 'react'
import styled from 'styled-components'

export function Modal({ show, children }) {
  return (
    <DivModal show={show}>
      {children}
    </DivModal>
  )
}

const DivModal = styled.div`
  display: ${props => (props.show ? 'block' : 'none')};
`

How to fire event's only for modal itself? 如何触发事件仅针对模式本身?

Ehh, this work, but if you click on wraper div - modal will not hide :( 恩,这项工作不错,但是如果您点击wrapper div-模式将不会隐藏:(

After some googling ant try, found a way. 经过一些谷歌搜索蚂蚁的尝试,找到了一种方法。 Key point is that you need to stop onClick event propagation from parent to childrens. 关键是您需要停止onClick事件从父级传播到子级。 In my case i just wrapped my component by div with onClick={e => e.stopPropagation()}. 就我而言,我只是用onClick = {e => e.stopPropagation()}按div包装了我的组件。

import React from 'react'
import styled from 'styled-components'

export function Modal({ show, showModalSet, children }) {
  return (
    <DivModal onClick={() => showModalSet(false)} show={show}>
      <div onClick={e => e.stopPropagation()}>{children}</div>
    </DivModal>
  )
}

const DivModal = styled.div`
   position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.8);
  display: ${({ show }) => (show ? 'block' : 'none')};
  z-index: 10;
  overflow-y: scroll;
`

Component use: 组件用途:

<Modal show={showModal} showModalSet={showModalSetFunctionInUsePlace}>

Another approach, that i'am happy now with is to use refs and compare what component was clicked: 我现在很高兴的另一种方法是使用引用并比较单击了哪个组件:

import React, { useRef } from 'react'
import styled from 'styled-components'

export function Modal({ show, showModalSet, children }) {
  const modalRef = useRef(null)

  function handleClick(e) {
    if (e.target == modalRef.current) showModalSet(false)
  }

  return (
    <DivModal onClick={handleClick} show={show} ref={modalRef}>
      {children}
    </DivModal>
  )
}

const DivModal = styled.div`
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.8);
  display: ${({ show }) => (show ? 'block' : 'none')};
  z-index: 10;
  overflow-y: scroll;
`

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

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