如何修改 html 模板中元素的属性?

How can I modify properties of an element inside an html template?

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

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

我想在 myTemplate 中添加一个 属性。

类似

myTemplate.foo = "bar"

但这引用了模板而不是元素;如何隔离元素以对其进行修改?

据我所知,你不能,至少你尝试的方式不行(至少使用 public 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';

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

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});