You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React中正确程序化渲染Lit Web组件?

问题:如何在React中正确显示Lit Web组件?

我拥有一个可渲染输入框的简单Lit Web组件,代码如下:

import {html} from "lit-element";
import {customElement} from 'lit/decorators.js';
import "./plain-text";

export class MyInputText {
    constructor(args){
        this.args = args;
    }
    
    createPreview(){
        const {
            colorScheme,
            disabled,
            labelText,
            value,
            size,
            customizeStyles
        } = this.args? this.args: {};
        return html`
        <plain-text
                color-scheme="${colorScheme}"
                ?disabled="${disabled}"
                label-text="${labelText}"
                value="${value}"
                size="${size}"
                customizeStyles="${customizeStyles}"></plain-text>
    `;
    }
    
    propertyChanged(propertyName, propertyValue){
        this.args = {...this.args, [propertyName]:propertyValue}
        return this.createPreview();
    }
    
};

我尝试通过以下代码在React中程序化加载该组件:

let el = new PlainTextPreviewUI.PlainTextPreview();
el.propertyChanged("width", "300px");
return el;

执行后返回Lit的html模板对象,渲染时出现错误:

Uncaught Error: Objects are not valid as a React child (found: object with keys {strings, values, type, processor}). If you meant to render a collection of children, use an array instead.

请问如何在React中正确显示这个Web组件?


解决方法

你当前的核心问题是直接返回了Lit专属的html模板对象,React无法识别这种结构,必须转换为真实DOM元素或直接使用Web组件标签。

方案一:直接在React中渲染<plain-text>标签

React支持直接渲染自定义Web组件,无需通过MyInputText类的模板方法。直接在React组件中写:

// 先确保Web组件已被导入注册
import './path-to-your-plain-text-component';

function ReactInputWrapper() {
  // 示例:用状态管理属性
  const [width, setWidth] = useState('300px');

  return (
    <plain-text
      color-scheme="light"
      disabled={false}
      label-text="用户名"
      value="初始内容"
      size="medium"
      customize-styles={`width: ${width}`}
    ></plain-text>
  );
}
  • 注意:Web组件的属性名在JSX中要改用kebab-case(比如customize-styles而非customizeStyles),React会自动转换为对应的DOM属性。
  • 布尔属性(如disabled)直接传布尔值即可,React会处理成Web组件的布尔属性。

方案二:通过MyInputText类生成DOM后挂载

如果必须复用现有的MyInputText类,需要用Lit的render方法把模板转换成真实DOM,再挂载到React节点中:

import { render } from 'lit';
import { MyInputText } from './path-to-MyInputText';

function ReactInputWrapper() {
  const containerRef = useRef(null);

  useEffect(() => {
    // 初始化实例
    const inputInstance = new MyInputText({
      width: '300px',
      labelText: "用户名"
      // 其他初始参数
    });
    // 将Lit模板渲染到React的ref容器里
    render(inputInstance.createPreview(), containerRef.current);

    // 示例:后续更新属性
    setTimeout(() => {
      inputInstance.propertyChanged("width", "400px");
      render(inputInstance.createPreview(), containerRef.current);
    }, 2000);
  }, []);

  return <div ref={containerRef}></div>;
}

关键注意点

  • React不能直接渲染Lit的html模板对象,必须转换为真实DOM或直接使用Web组件标签。
  • 确保plain-text组件已通过customElement装饰器完成注册(导入后会自动执行注册逻辑)。

内容的提问来源于stack exchange,提问作者Amelita

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 15:24:40