自React 19宣告即将发布更新以来,各路文章分析和其他框架的差异,引来前端娱乐圈的一波又一波骂战。却鲜少有文章提到React 19的重大更新:针对Custom Elements的100%支持。
本文通过例子测试一下:
使用SolidJS编写Web Components
为什么选择SolidJS ?因为它使用JSX,且非常容易转换成Web Components。
新建一个Solid组件:
// Button.jsx
const Button = (props) => {
const onClick = () => {
props.onClick && props.onClick()
}
return <button onClick={onClick}>Solid编写的Web Component。数字{props.name}由外部传进</button>
}
export default Button
然后进行导出,并通过solid-element 转换成Web Components:
// index.js
import { customElement } from "solid-element"
import Button from './Button.jsx'
customElement('my-button', {name: '', onClick: void 0,}, Button)
export default Button
打包之后就完成了一个Web Components的编写,接下来在React 19中使用:
React 19中使用Web Components
安装React 19的依赖:
npm install --save-exact react@rc react-dom@rc
编写React页面使用上面打包好的组件:
// App.jsx
import {useState} from 'react'
import Button from "my-web-components-library"
const App = () => {
const [state, setState] = useState(0)
const handleChange = () => {
setState(state+1)
}
return (
<div className="content">
<my-button name={state} onClick={handleChange}></my-button>
<span>React中的值{state}</span>
</div>
);
};
export default App;
下面是执行效果:
展望未来
React 19之前的版本由于种种原因对Web Components的支持不甚友好,需要经过封装才能使用。本次大版本更新后不需要多少改造即可进行使用,可谓“史诗级”更新。自此React、Angular、Vue、Svelte、Solid几大山头均支持Web Components了。是时候学起来了朋友们,一套UI组件库通用各框架的未来已来。