如何将价值从 React 传递给 lit-element 道具

How to pass value from react to lit-element props

我正在尝试在我的 React 项目中调用一个 lit-element 组件,并想将一个值传递给 props 到 React 中的一个 lit-element 组件,但没有成功。我的意思是道具 .config。在反应中我不能使用点。有可能以某种方式绕过它并将值传递给 props .config?

小元素示例:

<custom-tooltip .config=${{ position: 'right' }}>
  <custom-button slot="invoker" class="demo-tooltip">Settings</custom-button>
  <div slot="content">Settings and preferences<div>
</custom-tooltip>

我的反应代码:

<custom-tooltip> //in this place .config={} not working
    {this.props.children}
    <div slot="content">{this.props.text}</div>
</custom-tooltip>

. 用于属性 lit-element 模板中的绑定。它在 JSX 中不起作用。

一旦您在 lit-element 中使用 @Property() 定义了带有 属性 的组件,则可以直接从 html 分配 属性。 在这种情况下,您想使用 JSX 的绑定语法。

这很简单:

<custom-tooltip config={{ position: 'right' }}> 
    {this.props.children}
    <div slot="content">{this.props.text}</div>
</custom-tooltip>

你说得对,你不能在 React 中使用点。另一个问题是 React 实际上并没有设置元素“属性”,而只是设置属性。属性只是字符串,因此您不能像使用任何其他 React 组件或 JSX 那样将对象、数组或函数传递给您的 Web 组件。

这就是为什么

<custom-tooltip config={{ position: 'right' }}>

无效。

但是,lit-element 能够为您转换这些字符串,只要您告诉它该怎么做。

首先,您需要确保在 custom-tooltip 元素中声明 config 属性。这样 lit-element 就可以正确地跟踪和转换 属性。像这样

@property({ type: Object }) config

现在,您有两个选择。

首先,您可以将其作为正确字符串化的对象传递。

<custom-tooltip config={'{ "position": "right" }'}>

或者其次,您可以使用 reactify-wc

这样的库
const CustomTooltip = reactifyWc("custom-tooltip");
    
<CustomTooltip config={{ position: 'right' }}>

使用“对 Web 组件做出反应”库可以轻松做到这一点,因此您无需担心,只需像使用任何其他 JSX 一样在 JSX 中使用 Web 组件即可。如果您知道需要将大量非字符串属性从 React 组件传递到 Web 组件,我会建议这样做。