lit-html / lit-element中的类似React的引用?

时间:2019-11-26 02:11:08

标签: lit-element lit-html

lit-html是否有任何变化,例如React的ref功能? 例如,在下面的伪代码inputRef中将是一个回调函数或一个对象{ current: ... },在创建/附加输入元素时,lit-html可以传递/设置输入元素的HTMLElement实例。

// that #ref pseudo-attribute is fictional
html`<div><input #ref={inputRef}/></div>`

谢谢。

3 个答案:

答案 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>`

在我的用例中,我可以执行以下操作:

  1. 渲染之前,将elementRef.current设置为null
  2. 请确保在重新渲染组件时无法读取elementRef.current(渲染时不需要elementRef.current,如果有人尝试在渲染阶段读取它,则会抛出异常)
  3. elementRef.bind指令将使用实际的DOM元素填充elementRef.current(如果有)。
  4. 之后,elementRef.current可以再次读取。