React如何忽略子元素的onClick事件

4

我有一个子组件在父组件内。我想要当我点击父级组件除子组件之外的任意地方时弹出消息。

class TodoApp extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
    }
  }

  render() {
    return (
      <div className="parent" onClick={() => alert('x')}>
        <p>Alert clicks anywhere on this div</p>
        <div className="children">
          <button>Do not alert On this element click</button>
        </div>
        <p>Alert clicks anywhere on this div</p>
      </div>
    )
  }
}

以下为代码示例:

http://jsfiddle.net/rgL5f9yh/

3个回答

18

在子元素的onClick属性中添加e.stopPropagation()。

class TodoApp extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
    }
  }

  render() {
    return (
      <div className="parent" onClick={() => alert('x')}>
        <p>Alert clicks anywhere on this div</p>
        <div onClick={(e) => e.stopPropagation()} className="children">
          <button>Do not alert On this element click</button>
        </div>
        <p>Alert clicks anywhere on this div</p>
      </div>
    )
  }
}

7
你可以在子元素中阻止事件传播,即
<button onClick={((e) => e.stopPropagation())}>Do not alert On this element click</button>

0
更好的方法是设置一个引用,只响应该元素上的点击。
export function Blanket({
  children,
  onClick,
}: PropsWithChildren<{ onClick?: () => void; }>) {
  const blanketRef = createRef<HTMLDivElement>();

  const handleCloseClick: MouseEventHandler<HTMLDivElement> = (event) => {
    if (typeof onClick !== "function") return;

    // begin type narrowing
    if (event.target !== blanketRef.current) return;

    event.stopPropagation();
    onClick();
  };

  return (
    <div
      ref={blanketRef}
      style={{
         width: '100%'
         zIndex: 1000,
         display: 'flex',
         flexDirection: 'column',
         alignItems: 'center',
         justifyContent: 'center',
         position: 'fixed',
         top: 0,
         bottom: 0,
         left: 0,
         right: 0,
         background: '#00000033'
      }}
      onClick={handleCloseClick}
    >
      {children}
    </div>
  );
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接