【问题标题】:How can I modify properties of an element inside an html template?如何修改 html 模板中元素的属性?
【发布时间】:2021-11-07 01:54:12
【问题描述】:

我有一个 html 模板存储在一个变量中:

const myTemplate = html`
    <my-component>
    </my-component>
`

我想给myTemplate添加一个属性。

类似

myTemplate.foo = "bar"

但这引用了模板而不是元素;如何隔离元素来修改它?

【问题讨论】:

    标签: javascript html lit


    【解决方案1】:

    对于这种情况,您通常会使用返回模板的函数。

    const myTemplate = (props) => {
      return html`<my-component foo=${props.foo} .bar=${props.bar}></mycomponent>`;
    };
    const instance = myTemplate({foo: 'some value', bar: 3});
    const otherInstance = myTemplate({foo: 'other value', bar: 42});
    

    【讨论】:

    • 这就是我最终要做的,谢谢。限制是必须手动触发反应组件渲染。
    • 是的,除非您也使用包含所有更新生命周期的 LitElement 基类,否则您不会获得自动渲染的东西
    【解决方案2】:

    据我所知,您不能,至少不能尝试(至少使用公共 API)。

    最好的选择是简单地使用已经存在的选项来渲染它:

    const myTemplate = html`
        <my-component .foo=${'bar'}>
        </my-component>
    `;
    

    这应该是您 99.9% 的时间使用的方法。如果由于某种原因您真的无法做到这一点,您需要继续将模板渲染到某个占位符元素,然后使用 DOM 对其进行修改:

    const div = document.createElement('div');
    render(myTemplate, div);
    
    div.querySelector('my-component').foo = 'bar';
    

    【讨论】:

      猜你喜欢
      • 2021-05-27
      • 1970-01-01
      • 1970-01-01
      • 2017-10-13
      • 2015-04-23
      • 2010-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多