0%

react-use-lit-element-in-react-app

今天我们来学习一下如何在React项目中使用Lit Element,Lit Element是一个轻量级的Web Component库,因为基于标准的Web Component API, 所以它可以在任何支持Web Component的框架中使用,比如React、Vue、Angular等。

使用Vite创建React项目

首先使用Vite创建React项目,在命令行下运行如下命令:

1
npm create vite@latest lit-app-react-ts --template react-ts

提示framework的时候选择react,语言选择typescript

安装Lit Element

接下来运行以下命令来安装lit

1
npm install lit

更改tsconfig设置

tsconfig.json中添加以下配置:

1
2
3
4
5
6
{
"compilerOptions": {
"experimentalDecorators": true,
"useDefineForClassFields": false,
}
}

创建Lit Element组件

src目录下创建一个components目录,然后在components目录下创建一个my-element.ts文件,内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { LitElement, css, html } from 'lit';
import { customElement, property } from 'lit/decorators.js';

@customElement('my-element')
export class MyElement extends LitElement {
@property({ type: String }) name = 'World';

static styles = css`
:host {
display: block;
padding: 16px;
color: var(--my-element-text-color, black);
}
`;

render() {
return html`<p>Hello, ${this.name}!</p>`;
}
}

在App.tsx中使用Lit Element组件

src/App.tsx中引入并使用my-element组件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import './App.css';
import './components/my-element.ts';

function App() {

return (
<>
<h1>Hi</h1>
<my-element name="World"></my-element>
<p>This is a paragraph</p>
</>
)
}

export default App

运行项目

1
2
3
cd my-react-lit-app
npm install
npm run dev