您能否阻止嵌套子节点执行其构造函数直到父节点构造?

发布于 2025-02-02 02:55:11 字数 756 浏览 3 评论 0原文

想象一下一个场景,我有以下dom树的

<body>
  <parent-component>
    <div>
      <child-component></child-component>
    </div>
  </parent-component>
</body>

儿童组件具有seekparent函数,该功能启动了Customevent,应由&lt; parent; parent; parent-component&gt捕获;,然后使用回调告诉孩子这是父组件节点。

考虑何时通过customElements.define()首先定义子组件。定义了&lt; child-component&gt;,因此孩子的构造函数从customevent发射,因为父母节点在此阶段不需要有效,并且在此阶段为> htmlunknownelement

事件通过&lt; parent-component&gt;而没有被捕获,因为该组件尚未称为其构造函数,以附加事件侦听器。

直到父母定义 /有效元素之前,是否彻底不可解除DOM树中的子节点?否则,除了使用settimeout()之外,还有什么方法可以解决此问题?

谢谢

Imagine a scenario where I have the following DOM tree

<body>
  <parent-component>
    <div>
      <child-component></child-component>
    </div>
  </parent-component>
</body>

The child component has a seekParent function that fires off a CustomEvent that should be caught by the <parent-component>, which then uses a callback to tell the child this is the parent component node.

Consider when the child component is is defined via customElements.define() first. The child's constructor fires off the CustomEvent as soon as <child-component> is defined, since parent nodes do not need to be valid and at this stage be HTMLUnknownElement.

The event bubbles through the <parent-component> without being caught because that component has not yet called its constructor, to attach an event listener.

Is it at all possible to not parse child nodes within a DOM tree until a parent becomes defined / valid Element? Otherwise, is there any way around this issue besides using a setTimeout()?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

旧夏天 2025-02-09 02:55:11

也许您可以制作一个延迟渲染直到安装的组件:

class ParentComponent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      mounted: false,
    }
  }

  componentDidMount() {
    this.setState({mounted: true});
  }

  render() {
    if (!this.state.mounted) return null;

    return this.props.children;
  }
}

Perhaps you could make a component that delays the rendering until it's mounted:

class ParentComponent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      mounted: false,
    }
  }

  componentDidMount() {
    this.setState({mounted: true});
  }

  render() {
    if (!this.state.mounted) return null;

    return this.props.children;
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文