Javascript React hooks onClick fire仅适用于父级(模态)
我有一个模态窗口,如果用户点击了模态窗口本身的黑色背景,我希望它隐藏起来,但点击是由clildrens触发的。以下是一个例子:Javascript React hooks onClick fire仅适用于父级(模态),javascript,reactjs,Javascript,Reactjs,我有一个模态窗口,如果用户点击了模态窗口本身的黑色背景,我希望它隐藏起来,但点击是由clildrens触发的。以下是一个例子: import React, { useState, useEffect } from 'react' import styled from 'styled-components' export function Modal({ show, children }) { return ( <DivModal show={show}> {
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')};
`
如何仅为modal本身触发事件?Ehh,这项工作可以完成,但如果您单击wraper div,modal将不会隐藏: 经过一些谷歌蚂蚁的尝试,找到了一种方法。关键的一点是,您需要停止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}>
另一种我现在很高兴的方法是使用refs并比较单击的组件:
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;
`