ReactJS:在父组件的子组件中禁用鼠标事件

Luc*_*hux 3 event-handling reactjs

我有一个像这样的组件层次结构:

<parent>
   <someWrapper1>
        <child>
        <child>
   <someWrapper2>
       <child>
       <child>
Run Code Online (Sandbox Code Playgroud)

每个子组件自己处理一堆鼠标事件,其中一些是 D3 包装器管理onDragStartonClick鼠标事件。

我正在寻找一种方法来根据父组件的状态禁用<someWrapper1/><someWrapper2/>组件以及组件中的所有鼠标事件<child/>

一种解决方案是将 disable 的 prop 传递给包装器组件,并将它们传递给每个子组件,然后传递给每个处理程序以禁用或启用鼠标事件。我想避免这种情况,因为它很难维护。

我正在寻找一个更好的解决方案,我可以在其中禁用父组件中所有组件中的所有鼠标事件。

谢谢!

Dac*_*nny 5

如果我理解正确,您希望在 DOM 的特定子树上禁用鼠标事件。在这种情况下,您可以使用 CSSpointer-events: none;规则来实现这一点。

例如,要限制元素/组件及其子元素上的鼠标事件,您可以创建一个带有pointer-events键和none值的样式对象,并将其应用于<someWrapper1>组件以动态启用/禁用这些组件(及其后代)上的鼠标事件:

/* Your components render method */
render() {

    /* Acquire the disableEvents value from state, etc */
    const disableEvents = true;

    /* Dynamically compute style for wrapper components 
       to control mouse interactivity */
    const wrapperStyle = { 
        "pointer-events": disableEvents ? "none" : "unset" 
    };

    /* Apply dynamic styles to wrappers. When disableEvents 
       is true, mouse events will be disabled on someWrapper1
       and child descendants */
    return (<parent>
        <someWrapper1 style={wrapperStyle}>
            <child />
            <child />
        </someWrapper1>
        <someWrapper1 style={wrapperStyle}>
            <child />
            <child />
        </someWrapper1>
    </parent>)

}
Run Code Online (Sandbox Code Playgroud)

  • 是的,您可以将“pointer-events: none”应用到文档的“body”元素来实现这一点 (2认同)