我试图在我的 React 项目中调用 lit-element 组件,并希望将 props 的值从 React 传递到 lit-element 组件中,但没有成功。我的意思是关于 props .config。在 react 中我不能使用点。是否可以以某种方式绕过它并将值传递给 props .config?
Lit元素示例:
<custom-tooltip .config=${{ position: 'right' }}>
<custom-button slot="invoker" class="demo-tooltip">Settings</custom-button>
<div slot="content">Settings and preferences<div>
</custom-tooltip>
我的 react 代码:
<custom-tooltip> //in this place .config={} not working
{this.props.children}
<div slot="content">{this.props.text}</div>
</custom-tooltip>
最佳答案
你是对的,你不能在 React 中使用点。另一个问题是 React 实际上并没有设置元素“属性”,而只是设置属性。属性只是字符串,因此您无法像使用任何其他 React 组件或 JSX 那样将对象、数组或函数传递给 Web 组件。
这就是原因
<custom-tooltip config={{ position: 'right' }}>
不起作用。
但是,如果您告诉lit-element 要做什么,lit-element 就可以为您转换这些字符串。
首先,您需要确保声明 config
您的属性(property)custom-tooltip
元素。这样 lit-element 就可以正确跟踪和转换属性。像这样
@property({ type: Object }) config
现在,您有两个选择。
首先,您可以将其作为正确的字符串化对象传递。
<custom-tooltip config={'{ "position": "right" }'}>
或者其次,您可以使用像 reactify-wc 这样的库
const CustomTooltip = reactifyWc("custom-tooltip");
<CustomTooltip config={{ position: 'right' }}>
使用“对 Web 组件使用react”库可以轻松做到这一点,因此您无需担心它,只需在 JSX 中使用 Web 组件,就像使用任何其他 JSX 一样。如果您知道需要将大量非字符串属性从 React 组件传递到 Web 组件,我建议您这样做。
关于javascript - 如何将值从react传递到lit-element props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66457013/