@thinke/solidjs-on-react
v0.1.3
Published
让 SolidJS 和 React 共存
Readme
@thinke/solidjs-on-react
该项目旨在结合 React 的生态系统和 SolidJS 的性能优势:
- React:强大的生态系统和社区支持
- SolidJS:高性能的响应式编程模型
通过此方案,您可以在现有 React 项目中逐步引入 Solid 组件
安装
pnpm add @thinke/solidjs-on-react配置 vite.config.ts
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite'
import babel from 'vite-plugin-babel'
import solid from 'vite-plugin-solid'
const solidFiles = '**/*.solid.(ts|tsx)'
// https://vite.dev/config/
export default defineConfig({
plugins: [
babel({
include: solidFiles,
filter: () => true,
enforce: 'pre',
babelConfig: {
babelrc: false,
configFile: false,
plugins: [
['@thinke/babel-plugin-solidjs-on-react', {}],
],
parserOpts: {
plugins: ['jsx', 'typescript'],
},
},
}),
react({ exclude: solidFiles }),
solid({
include: solidFiles,
solid: {
generate: 'universal',
moduleName: '@thinke/solidjs-on-react',
},
hot: false,
}),
],
})解决类型冲突
在 main.tsx 修改类型,不让react和solidjs类型冲突
import type { ReactNode } from 'react'
declare module 'solid-js' {
namespace JSX {
// 解决 solid-js 与 react 的类型冲突
type Node = ReactNode
}
}使用示例
创建 Solid 组件 (Counter.solid.tsx)
import { createSignal } from 'solid-js'
export default function Counter() {
const [count, setCount] = createSignal(0)
return (
<div class="p-4 border rounded">
<h2 class="text-lg font-medium mb-2">Solid Counter</h2>
<button
class="px-4 py-2 bg-blue-500 text-white rounded"
onClick={() => setCount(count() + 1)}
>
Count: {count()}
</button>
</div>
)
}在 React 组件中使用
import React from 'react'
import Counter from './Counter.solid'
function App() {
return (
<div class="p-6 max-w-md mx-auto">
<h1 class="text-2xl font-bold mb-4">React App with Solid Component</h1>
<Counter />
</div>
)
}
export default AppAPI
withSolid HOC
import { withSolid } from '@thinke/solidjs-on-react/withSolid'
const ReactComponent = withSolid(SolidComponent)Props 传递
所有传递给包装组件的 props 都会作为 Solid 组件的 props
注意事项
- 文件命名约定:Solid 组件文件必须以
.solid.tsx结尾,也可自行配置 - 状态管理:在 Solid 组件中使用
createSignal等 Solid 原生 API
可能出现的问题排查
数据不更新
可以使用 React Developer Tools 里的 Components 页面查看节点的key是否类似notOwner:xxxx。
如果是则此节点未能获取到正确的owner ,不会更新。
可在组件渲染前打开log globalThis.__solid_on_react__log = true ,查看具体log
