Code Editor — React
@aiao/code-editor-react 提供标准 React 受控组件。
安装
- npm
- Yarn
- pnpm
- Bun
npm install @aiao/code-editor-react
yarn add @aiao/code-editor-react
pnpm add @aiao/code-editor-react
bun add @aiao/code-editor-react
Peer dependencies: react >= 18
基础用法
import { useState } from 'react';
import { CodeEditor } from '@aiao/code-editor-react';
function App() {
const [code, setCode] = useState('SELECT * FROM users;');
return <CodeEditor value={code} onChange={setCode} language="sql" theme="dark" lineWrapping />;
}
组件 Props
interface CodeEditorProps {
value?: string;
onChange?: (value: string) => void;
theme?: 'light' | 'dark';
language?: string;
placeholder?: string;
readonly?: boolean;
disabled?: boolean;
setup?: 'basic' | 'minimal';
indentWithTab?: boolean;
indentUnit?: string;
lineWrapping?: boolean;
highlightWhitespace?: boolean;
}
| Prop | 类型 | 默认值 | 说明 |
|---|---|---|---|
value | string | '' | 编辑器内容 |
onChange | (value: string) => void | — | 内容变化回调 |
theme | 'light' | 'dark' | 'light' | 主题 |
language | string | 'sql' | 语言名称 |
placeholder | string | — | 占位文本 |
readonly | boolean | false | 只读模式 |
disabled | boolean | false | 禁用编辑 |
setup | 'basic' | 'minimal' | 'basic' | 预设扩展包 |
indentWithTab | boolean | false | Tab 缩进 |
indentUnit | string | — | 缩进单位 |
lineWrapping | boolean | false | 自动换行 |
highlightWhitespace | boolean | false | 高亮空白字符 |
受控模式
React 版本为受控组件,外部 value 变化时内部对比避免循环更新:
function SqlEditor({ initialSql }: { initialSql: string }) {
const [sql, setSql] = useState(initialSql);
const [result, setResult] = useState('');
const handleRun = async () => {
const res = await executeQuery(sql);
setResult(JSON.stringify(res, null, 2));
};
return (
<div className="flex flex-col gap-4">
<CodeEditor value={sql} onChange={setSql} language="sql" />
<button onClick={handleRun}>执行</button>
<CodeEditor value={result} language="json" readonly />
</div>
);
}