高端網(wǎng)站開(kāi)發(fā)程推廣賺錢的微信小程序
在svelet5中導(dǎo)入并使用react組件庫(kù)
- svelte5中使用react組件
svelte5中使用react組件
在svelet5中導(dǎo)入并使用react組件庫(kù), 示例項(xiàng)目地址:https://github.com/shenshouer/my-svelte-react
在svelte5中當(dāng)前還有問(wèn)題,無(wú)法將children傳遞到react中渲染
- 使用svletkit創(chuàng)建項(xiàng)目
$ npx sv create my-svelte-react% npx sv create my-svelte-react
┌ Welcome to the Svelte CLI! (v0.6.10)
│
◇ Which template would you like?
│ SvelteKit minimal
│
◇ Add type checking with Typescript?
│ Yes, using Typescript syntax
│
◆ Project created
│
◇ What would you like to add to your project? (use arrow keys / space bar)
│ none
│
◇ Which package manager do you want to install dependencies with?
│ pnpm
│
◆ Successfully installed dependencies
│
◇ Project next steps ─────────────────────────────────────────────────────╮
│ │
│ 1: cd my-svelte-react │
│ 2: git init && git add -A && git commit -m "Initial commit" (optional) │
│ 3: pnpm run dev --open │
│ │
│ To close the dev server, hit Ctrl-C │
│ │
│ Stuck? Visit us at https://svelte.dev/chat │
│ │
├──────────────────────────────────────────────────────────────────────────╯
│
└ You're all set!$ cd my-svelte-react$ pnpm install$ pnpm dev
- 安裝react相關(guān)依賴
$ pnpm i react react-dom
$ pnpm i --save-dev @types/react @types/react-dom
$ pnpm add @vitejs/plugin-react -D
- 修改
vite.config.ts
增加react支持
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react'; # <---- hereexport default defineConfig({plugins: [sveltekit(), react()] # <---- here
});
- 創(chuàng)建react svelte適配器
ReactAdapter.svelte
, 代碼如下:
# src/lib/utils/ReactAdapter.svelte<script lang="ts">import React from "react";import ReactDOM from "react-dom/client";import { onDestroy, onMount } from "svelte";const e = React.createElement;let container: HTMLElement;let root: ReactDOM.Root;onMount(() => {const { el, children, class: _, ...props } = $$props;try {root = ReactDOM.createRoot(container);root.render(e(el, props, children));} catch (err) {console.warn(`react-adapter failed to mount.`, { err });}});onDestroy(() => {try {if (root) {root.unmount();}} catch (err) {console.warn(`react-adapter failed to unmount.`, { err });}});
</script><div bind:this={container} class={$$props.class}></div>
目前此部分適配器有問(wèn)題, children無(wú)法獲取并且在react組件中渲染
參考:
props-and-restProps
issues
- 添加react組件庫(kù), 如 ant design
$ pnpm add antd# +page.svelte<script lang="ts">import { Button } from "antd";import ReactAdapter from "$lib/utils/ReactAdapter.svelte";
</script><ReactAdapter el={Button} type="primary">Hello, World!</ReactAdapter>