react-live: react组件预览

一个方便预览react组件的工具
更新于: 2024-05-22 09:55:08

安装

yarn add --dev react-live

文件结构

├── App.tsx
├── components
│   ├── component-a.tsx
│   └── component-b.tsx
├── live.jsx
├── main.tsx
└── vite-env.d.ts

live.jsx

  • /* eslint-disable */ 防止报错。
/* eslint-disable */
<div className="y-2 *:debug-red">
  <h3
    style={{
      background: 'darkslateblue',
      color: 'white',
      padding: 8,
      borderRadius: 4
    }}>
    Hello World! 👋
  </h3>
  <ComponentA />
  <ComponentB />
</div>;

App.tsx

特别留意 scope 的设置。

import { LiveProvider, LiveEditor, LivePreview, LiveError } from 'react-live';
import code from './live.jsx?raw';
import React, { useState, useRef, useReducer } from 'react';
import ComponentA from './components/component-a';
import ComponentB from './components/component-b';

function App() {
  return (
    <div className="mx-auto mt-20 w-1/2 flex-col rounded-md bg-slate-200 p-5 shadow-md y-2">
      <h1>Live Code Editor</h1>
      <LiveProvider
        code={code}
        scope={{
          React,
          useState,
          useRef,
          useReducer,
          ComponentA,
          ComponentB
        }}>
        <div className="y-2">
          <LiveError className="text-red-600" />
          <div className="grid grid-cols-2 gap-4">
            <LiveEditor className="font-mono" />
            <LivePreview />
          </div>
        </div>
      </LiveProvider>
    </div>
  );
}

export default App;

在线 demo

参考