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

Nat*_*sha 5 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>`

Run Code Online (Sandbox Code Playgroud)

谢谢。

lis*_*ine 12

在 lit-element 中,您可以使用@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>
    `;
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 这个解决方案似乎是最简洁、直接、有用的。 (2认同)

Nat*_*sha 6

正如 @WeiChing 上面提到的,从 Lit 2.0 版本开始,您可以使用新添加的指令ref: https: //lit.dev/docs/templates/directives/#ref


Ala*_*los 5

lit-html 直接渲染到 dom,因此您不需要像在 React 中那样真正需要 ref,您可以使用它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>
Run Code Online (Sandbox Code Playgroud)

如果您使用 LitElement,则可以使用是否使用 Shadow dom 来访问内部this.shadowRoot.querySelector元素this.querySelector