lit-html是否有任何变化,例如React的ref
功能?
例如,在下面的伪代码inputRef
中将是一个回调函数或一个对象{ current: ... }
,在创建/附加输入元素时,lit-html可以传递/设置输入元素的HTMLElement实例。
// that #ref pseudo-attribute is fictional
html`<div><input #ref={inputRef}/></div>`
谢谢。
答案 0 :(得分:6)
在照明元素中,您可以使用@query
属性装饰器。只是this.renderRoot.querySelector()
周围的语法糖。
import { LitElement, html, query } from 'lit-element';
class MyElement extends LitElement {
@query('#first')
first;
render() {
return html`
<div id="first"></div>
<div id="second"></div>
`;
}
}
答案 1 :(得分:1)
lit-html直接呈现给dom,因此您不需要像在react中一样真正使用refs,可以使用querySelector
获取对呈现输入的引用
如果您仅使用lit-html,这里有一些示例代码
<html>
<head>
<title>lit-html example</title>
<script type="module">
import { render, html } from 'https://cdn.pika.dev/lit-html/^1.1.2';
const app = document.querySelector('.app');
const inputTemplate = label => {
return html `<label>${label}<input value="rendered input content"></label>`;
};
// rendering the template
render(inputTemplate('Some Label'), app);
// after the render we can access it normally
console.log(app.querySelector('input').value);
</script>
</head>
<body>
<div class="app"></div>
<label>
Other random input
<input value="this is not the value">
</label>
</body>
</html>
如果您使用的是LitElement,则可以使用this.shadowRoot.querySelector
来访问内部元素,如果您使用的是影子dom,则可以使用this.querySelector
来访问内部元素
答案 2 :(得分:1)
即使这不是我所要求的:
根据具体用例,要考虑的一种选择是使用directives。
在我非常特殊的用例中,例如(有一点运气和一些技巧)可以或多或少地模拟ref对象的行为。
const inputRef = useElementRef() // { current: null, bind: (special-lit-html-directive) }
...
return html`<div><input ref=${inputRef.bind}/></div>`
在我的用例中,我可以执行以下操作:
elementRef.current
设置为null
elementRef.current
(渲染时不需要elementRef.current
,如果有人尝试在渲染阶段读取它,则会抛出异常)elementRef.bind
指令将使用实际的DOM元素填充elementRef.current
(如果有)。elementRef.current
可以再次读取。