gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 02:49:07 25 4
gpt4 key购买 nike

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

<parent>
<someWrapper1>
<child>
<child>
<someWrapper2>
<child>
<child>

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

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

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

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

谢谢!

最佳答案

如果我理解正确,您希望在 DOM 的特定子树上禁用鼠标事件。在这种情况下,您可以使用 CSS pointer-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>)

}

关于ReactJS:在父组件的子组件中禁用鼠标事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55821045/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com