javascript - React hooks onClick 仅针对父级(模式)触发

标签 javascript reactjs

我有一个模态窗口,如果用户单击模态本身(黑色背景),我希望它隐藏,但单击是由 clildrens 触发的。这是示例:

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')};
`

如何仅针对模态本身触发事件?

最佳答案

呃,这个工作,但是如果你点击包装器 div - 模态将不会隐藏:(

经过一些谷歌 Ant 尝试,找到了一种方法。关键点是您需要停止 onClick 事件从父级到子级的传播。就我而言,我只是用 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;
`

组件使用:

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

关于javascript - React hooks onClick 仅针对父级(模式)触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54769109/

相关文章:

javascript - 在 OOP 中使用 Angular

javascript - 我的 ajax 代码显示评论时出现问题

javascript - jQuery datepicker maxDate 问题

javascript - 无法在命令提示符下使用 openai

javascript - 如何自动向 React 元素添加适当的类名

javascript - 如何在 React/jsx 中以三元组的形式显示真实情况下的组件和变量?

javascript - 如何将选项卡设置为选中

javascript - 使用 jQuery 创建/管理多维数组

node.js - fatal error : Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory when running a react app

javascript - 流类型检查 : undefined is not a function even if there is a conditional