我有一个模态窗口,如果用户单击模态本身(黑色背景),我希望它隐藏,但单击是由 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/