微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

由祖父母修改属性后,孙子组件插槽的内容不会重新呈现

如何解决由祖父母修改属性后,孙子组件插槽的内容不会重新呈现

我正在处理一个私人项目。

由于某种原因,无论父母或祖父母的属性如何变化,孙子都不会渲染。减去插槽的所有内容都会呈现正确的转换。翻译功能也可以使用,但是孙子拒绝渲染。

该项目需要下拉菜单才能更改语言。语言环境将通过属性向下传递。我已经验证了语言环境确实在孙代中更新了。

我在多个级别尝试过requestUpdate,但无法让孙子重新渲染广告位。

index.html:

<body>
    Locale:
    <select id="localeSelector">
      <option value="en_US" selected>en-us</option>
      <option value="es_MX">es-mx</option>
    </select>
    <my-element id="component"></my-element>
</body>

index.js:

import { LitElement,html,css } from "lit-element";

class ParentComponent extends LitElement {
  constructor() {
    super();
    this.__localeStrings = { test: "testing" };
    this.locale = "en_US";
  }

  update(changedProps) {
    super.update(changedProps);
    console.log("Parent: " + this.locale);
  }

  translate(key) {
    return this.__localeStrings[key];
  }

  static get properties() {
    return {
      locale: { type: String }
    };
  }

  render() {
    return html`
      <child-component .locale=${this.locale}></child-component>
    `;
  }
}

customElements.define("my-element",ParentComponent);

class ChildComponent extends LitElement {
  static get properties() {
    return {
      locale: { type: String }
    };
  }

  constructor() {
    super();
    this.__localeStrings = { en_US: "Hi",es_MX: "Hola",test: "testing" };
  }

  update(changedProps) {
    super.update(changedProps);
    console.log("Child: " + this.locale);
  }

  translate(key) {
    return this.__localeStrings[key];
  }

  render() {
    return html`
      <p>Always works: ${this.translate(this.locale)}</p>
      <great-child-component .locale=${this.locale}
        ><div name="content">
          ${this.translate(this.locale)}
        </div></great-child-component
      >
    `;
  }
}

customElements.define("child-component",ChildComponent);

class GreatChildComponent extends LitElement {
  static get properties() {
    return {
      locale: { type: String }
    };
  }

  constructor() {
    super();
  }

  update(changedProps) {
    super.update(changedProps);
    console.log("Great Child: " + this.locale);
  }

  render() {
    return html`
      <div>Current translation: <slot name="content"></slot></div>
    `;
  }
}

customElements.define("great-child-component",GreatChildComponent);

const localeSelector = document.querySelector("#localeSelector");
const mainElement = document.querySelector("#component");

/* ********************
 *** LOCALE SELECTOR ***
 ********************** */
const localeChangedActions = [];
localeChangedActions.push(locale => {
  mainElement.setAttribute("locale",locale);
});
localeSelector.onchange = () => {
  for (const action of localeChangedActions) {
    action(localeSelector.value);
  }
};

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。