react-draft-wysiwyg 和 react-quill 都是 React 生态中流行的富文本编辑器(WYSIWYG)解决方案,但它们的底层引擎和设计理念截然不同。react-draft-wysiwyg 基于 Facebook 的 Draft.js 构建,提供高度可定制的 React 组件化体验,但受限于底层库的归档状态。react-quill 则是成熟的 Quill 编辑器的 React 封装,拥有强大的富文本处理能力和稳定的 Delta 数据模型,适合需要复杂格式支持的生产环境。
在 React 项目中集成富文本编辑器是一个常见的架构决策。react-draft-wysiwyg 和 react-quill 曾经是两个最热门的选择,但它们的现状和适用场景已经发生了巨大变化。作为架构师,我们需要透过 API 表面,深入到底层引擎、数据模型和维护状态来评估风险。
这是两者之间最大的区别,也是决定性的架构风险。
react-draft-wysiwyg 依赖于 Draft.js。Facebook 已经正式归档(Archived)了 Draft.js 仓库,不再接受新功能或主要维护。这意味着底层引擎已经停止演进。
// react-draft-wysiwyg 依赖链
// react-draft-wysiwyg -> draft-js (Archived by Meta)
// 风险:底层不再修复安全漏洞或兼容新 React 版本
react-quill 依赖于 Quill.js。Quill 在经历了长期的 2.0 开发后,近期发布了正式版本,社区依然活跃,底层引擎仍在更新。
// react-quill 依赖链
// react-quill -> quill (Active Maintenance)
// 优势:底层持续修复 bug 并支持新特性
💡 架构建议:除非你正在维护一个无法迁移的旧系统,否则 不要 在新项目中使用
react-draft-wysiwyg。底层库的死亡意味着你的编辑器功能将被冻结在时间中。
编辑器如何存储和序列化数据,直接影响你的后端设计和数据迁移成本。
react-draft-wysiwyg 使用 Draft.js 的 ContentState。这是一种基于 Immutable.js 的复杂 JSON 结构。
// react-draft-wysiwyg: 导出原始 JSON
import { convertToRaw } from 'draft-js';
const rawContent = convertToRaw(editorState.getCurrentContent());
// 输出: { blocks: [...], entityMap: {...} }
// 缺点:结构复杂,难以直接转换为 HTML,依赖特定库解析
react-quill 使用 Delta 格式。这是一种简洁的操作数组,也可以轻松导出为 HTML。
// react-quill: 导出 Delta 或 HTML
const delta = quillRef.current.getDelta();
// 输出: { ops: [{ insert: "Hello" }, { insert: "World", attributes: { bold: true } }] }
const html = quillRef.current.root.innerHTML;
// 输出: "<p>Hello<strong>World</strong></p>"
// 优势:Delta 适合协作编辑,HTML 适合直接存储展示
当默认工具栏无法满足需求时,两者的扩展方式体现了不同的设计哲学。
react-draft-wysiwyg 允许你直接使用 React 组件来渲染自定义块。这对 React 开发者来说非常直观。
// react-draft-wysiwyg: 自定义块渲染
function MyCustomBlock(props) {
return <div className="custom-box">{props.children}</div>;
}
const editorProps = {
blockRendererFn: (block) => {
if (block.getType() === 'atomic') {
return {
component: MyCustomBlock,
editable: false,
};
}
}
};
<Editor editorState={state} onEditorStateChange={setState} {...editorProps} />
react-quill 使用 Quill 的 Blot 系统。这需要在 Quill 的注册表中定义,不能直接当作普通 React 组件使用,集成难度较高。
// react-quill: 自定义 Blot (需在 Quill 实例外注册)
import Quill from 'quill';
const BlockEmbed = Quill.import('blots/block/embed');
class MyEmbed extends BlockEmbed {
static create(value) {
let node = super.create();
node.setAttribute('data-id', value);
return node;
}
}
Quill.register(MyEmbed);
// 在 React 组件中使用
<ReactQuill modules={{ toolbar: [['my-embed', 'custom']] }} />
在大型表单或高频输入场景下,编辑器的渲染行为至关重要。
react-draft-wysiwyg 强依赖于 editorState 的受控模式。每次击键都会触发 React 状态更新,如果组件树过深,可能导致输入延迟。
// react-draft-wysiwyg: 典型的受控模式
const [editorState, setEditorState] = useState(EditorState.createEmpty());
// 每次 onChange 都会重新渲染整个 Editor 组件
<Editor
editorState={editorState}
onEditorStateChange={setEditorState}
/>
react-quill 支持非受控模式(通过 defaultValue)或混合模式,减少不必要的 React 渲染循环。它更多地依赖内部 DOM 管理。
// react-quill: 推荐的非受控或半受控模式
const quillRef = useRef(null);
// 仅在需要时获取内容,减少 React 重渲染
<ReactQuill
theme="snow"
defaultValue="<p>Initial content</p>"
ref={quillRef}
/>
// 提交时获取
const content = quillRef.current.editor.root.innerHTML;
尽管底层不同,两者都努力适应 React 的开发习惯。
两者都允许通过配置对象自定义工具栏。
// react-draft-wysiwyg
const toolbar = {
options: ['inline', 'blockType', 'list'],
inline: { options: ['bold', 'italic'] }
};
<Editor toolbar={toolbar} />
// react-quill
const modules = {
toolbar: [
[{ 'header': [1, 2, false] }],
['bold', 'italic']
]
};
<ReactQuill modules={modules} />
两者都需要引入 CSS 文件,且都支持通过类名覆盖默认样式。
/* 两者都需要全局 CSS 支持 */
@import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
@import 'react-quill/dist/quill.snow.css';
/* 自定义样式覆盖 */
.DraftEditor-root { font-family: 'CustomFont'; }
.ql-editor { font-family: 'CustomFont'; }
| 特性 | react-draft-wysiwyg | react-quill |
|---|---|---|
| 底层引擎 | Draft.js (已归档 ❌) | Quill.js (活跃 ✅) |
| 数据格式 | Immutable ContentState (JSON) | Delta (JSON) 或 HTML |
| 自定义扩展 | 原生 React 组件 (简单) | Quill Blots (较复杂) |
| React 集成 | 深度受控 (可能性能敏感) | 支持非受控 (性能较好) |
| 长期风险 | 高 (依赖已死) | 低 (社区维护) |
| 适用场景 | 遗留项目维护 | 新项目、复杂富文本需求 |
react-draft-wysiwyg 曾经是一个优秀的库,它让 Draft.js 变得易用。但如今,它就像一艘依赖已沉没引擎的船。在 2024 年及以后,选择它意味着你主动承担了底层库停止维护的风险。仅当你在维护一个无法重构的旧系统时,才继续使用它。
react-quill 是目前更务实的选择。虽然它的自定义扩展机制(Blots)不如纯 React 组件直观,但它提供了一个功能完整、经过生产验证的编辑引擎。对于大多数需要富文本功能的企业级应用,它是更安全的基础设施。
最终思考:富文本编辑器是前端最复杂的组件之一。如果可能,评估是否需要完整的 WYSIWYG。很多时候,基于 Markdown 的编辑器(如 react-markdown + Textarea)或更现代的 Headless 编辑器(如 Tiptap)可能是更好的架构选择,它们能提供更长的生命周期和更好的开发体验。
适合大多数需要稳定富文本编辑功能的新项目,特别是需要处理复杂格式(如表格、特定样式)的场景。虽然 Quill 的自定义扩展(Blots)学习曲线较陡,但其社区活跃且底层引擎持续更新。如果你需要更现代化的 React 集成体验,也可以考虑基于 ProseMirror 或 Tiptap 的替代方案,但在本对比中,它是更稳健的选择。
仅建议在维护基于 Draft.js 的遗留项目时选择此包。由于底层依赖 Draft.js 已被官方归档且不再维护,新项目使用它会面临长期的技术债务和安全风险。如果你的团队已经深度绑定 Draft.js 的数据结构且短期内无法迁移,它可以作为过渡方案,否则应避免在新架构中引入。
This is the documentation for ReactQuill v2 — Previous releases: v1
💯 ReactQuill v2
ReactQuill 2 is here, baby! And it brings a full port to TypeScript and React 16+, a refactored build system, and a general tightening of the internal logic.
We worked hard to avoid introducing any behavioral changes. For the vast majority of the cases, no migration is necessary at all. However, support for long-deprecated props, the ReactQuill Mixin, and the Toolbar component have been removed. Be sure to read the migration guide.
We expect this release to be a drop-in upgrade – if that isn't the case, please file an issue with the v2 label.
Make sure you have react and react-dom, and some way to load styles, like style-loader. See the documentation on themes for more information.
npm install react-quill --save
import React, { useState } from 'react';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
function MyComponent() {
const [value, setValue] = useState('');
return <ReactQuill theme="snow" value={value} onChange={setValue} />;
}
<link
rel="stylesheet"
href="https://unpkg.com/[email protected]/dist/quill.snow.css"
/>
<script
src="https://unpkg.com/react@16/umd/react.development.js"
crossorigin
></script>
<script
src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"
crossorigin
></script>
<script src="https://unpkg.com/[email protected]/dist/react-quill.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script type="text/babel" src="/my-scripts.js"></script>
In controlled mode, components are supposed to prevent local stateful changes, and instead only have them happen through onChange and value.
Because Quill handles its own changes, and does not allow preventing edits, ReactQuill has to settle for a hybrid between controlled and uncontrolled mode. It can't prevent the change, but will still override the content whenever value differs from current state.
If you frequently need to manipulate the DOM or use the Quill APIs imperatively, you might consider switching to fully uncontrolled mode. ReactQuill will initialize the editor using defaultValue, but won't try to reset it after that. The onChange callback will still work as expected.
Read more about uncontrolled components in the React docs.
You can pass a Quill Delta, instead of an HTML string, as the value and defaultValue properties. Deltas have a number of advantages over HTML strings, so you might want use them instead. Be aware, however, that comparing Deltas for changes is more expensive than comparing HTML strings, so it might be worth to profile your usage patterns.
Note that switching value from an HTML string to a Delta, or vice-versa, will trigger a change, regardless of whether they represent the same document, so you might want to stick to a format and keep using it consistently throughout.
⚠️ Do not use the delta object you receive from the onChange event as value. This object does not contain the full document, but only the last modifications, and doing so will most likely trigger an infinite loop where the same changes are applied over and over again. Use editor.getContents() during the event to obtain a Delta of the full document instead. ReactQuill will prevent you from making such a mistake, however if you are absolutely sure that this is what you want, you can pass the object through new Delta() again to un-taint it.
The Quill editor supports themes. It includes a full-fledged theme, called snow, that is Quill's standard appearance, and a bubble theme that is similar to the inline editor on Medium. At the very least, the core theme must be included for modules like toolbars or tooltips to work.
To activate a theme, pass the name of the theme to the theme prop. Pass a falsy value (eg. null) to use the core theme.
<ReactQuill theme="snow" .../>
Then, import the stylesheet for the themes you want to use.
This may vary depending how application is structured, directories or otherwise. For example, if you use a CSS pre-processor like SASS, you may want to import that stylesheet inside your own. These stylesheets can be found in the Quill distribution, but for convenience they are also linked in ReactQuill's dist folder.
Here's an example using style-loader for Webpack, or create-react-app, that will automatically inject the styles on the page:
import 'react-quill/dist/quill.snow.css';
The styles are also available via CDN:
<link
rel="stylesheet"
href="https://unpkg.com/[email protected]/dist/quill.snow.css"
/>
The Quill Toolbar Module API provides an easy way to configure the default toolbar icons using an array of format names.
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
text: "",
}
}
modules = {
toolbar: [
[{ 'header': [1, 2, false] }],
['bold', 'italic', 'underline','strike', 'blockquote'],
[{'list': 'ordered'}, {'list': 'bullet'}, {'indent': '-1'}, {'indent': '+1'}],
['link', 'image'],
['clean']
],
},
formats = [
'header',
'bold', 'italic', 'underline', 'strike', 'blockquote',
'list', 'bullet', 'indent',
'link', 'image'
],
render() {
return (
<div className="text-editor">
<ReactQuill theme="snow"
modules={this.modules}
formats={this.formats}>
</ReactQuill>
</div>
);
}
}
export default MyComponent;
You can also supply your own HTML/JSX toolbar with custom elements that are not part of the Quill theme.
See this example live on Codepen: Custom Toolbar Example
/*
* Custom "star" icon for the toolbar using an Octicon
* https://octicons.github.io
*/
const CustomButton = () => <span className="octicon octicon-star" />;
/*
* Event handler to be attached using Quill toolbar module
* http://quilljs.com/docs/modules/toolbar/
*/
function insertStar() {
const cursorPosition = this.quill.getSelection().index;
this.quill.insertText(cursorPosition, '★');
this.quill.setSelection(cursorPosition + 1);
}
/*
* Custom toolbar component including insertStar button and dropdowns
*/
const CustomToolbar = () => (
<div id="toolbar">
<select
className="ql-header"
defaultValue={''}
onChange={(e) => e.persist()}
>
<option value="1"></option>
<option value="2"></option>
<option selected></option>
</select>
<button className="ql-bold"></button>
<button className="ql-italic"></button>
<select className="ql-color">
<option value="red"></option>
<option value="green"></option>
<option value="blue"></option>
<option value="orange"></option>
<option value="violet"></option>
<option value="#d0d1d2"></option>
<option selected></option>
</select>
<button className="ql-insertStar">
<CustomButton />
</button>
</div>
);
/*
* Editor component with custom toolbar and content containers
*/
class Editor extends React.Component {
constructor(props) {
super(props);
this.state = { editorHtml: '' };
this.handleChange = this.handleChange.bind(this);
}
handleChange(html) {
this.setState({ editorHtml: html });
}
render() {
return (
<div className="text-editor">
<CustomToolbar />
<ReactQuill
onChange={this.handleChange}
placeholder={this.props.placeholder}
modules={Editor.modules}
/>
</div>
);
}
}
/*
* Quill modules to attach to editor
* See http://quilljs.com/docs/modules/ for complete options
*/
Editor.modules = {
toolbar: {
container: '#toolbar',
handlers: {
insertStar: insertStar,
},
},
};
/*
* Quill editor formats
* See http://quilljs.com/docs/formats/
*/
Editor.formats = [
'header',
'font',
'size',
'bold',
'italic',
'underline',
'strike',
'blockquote',
'list',
'bullet',
'indent',
'link',
'image',
'color',
];
/*
* PropType validation
*/
Editor.propTypes = {
placeholder: React.PropTypes.string,
};
/*
* Render component on page
*/
ReactDOM.render(
<Editor placeholder={'Write something or insert a star ★'} />,
document.querySelector('.app')
);
The component has two types of formats:
formats prop. All formats are enabled by default.import ReactQuill, { Quill } from 'react-quill'; // ES6
const ReactQuill = require('react-quill'); // CommonJS
/*
* Example Parchment format from
* https://quilljs.com/guides/cloning-medium-with-parchment/
* See the video example in the guide for a complex format
*/
let Inline = Quill.import('blots/inline');
class BoldBlot extends Inline {}
BoldBlot.blotName = 'bold';
BoldBlot.tagName = 'strong';
Quill.register('formats/bold', BoldBlot);
const formats = ['bold']; // add custom format name + any built-in formats you need
/*
* Editor component with default and custom formats
*/
class MyComponent extends React.Component {
constructor(props) {
this.formats = formats;
this.state = { text: '' };
}
handleChange(value) {
this.setState({ text: value });
}
render() {
return (
<ReactQuill
value={this.state.text}
onChange={this.handleChange}
formats={this.formats}
/>
);
}
}
If you instantiate ReactQuill without children, it will create a <div> for you, to be used as the editing area for Quill. If you prefer, you can specify your own element for ReactQuill to use. Note that <textarea>s are not supported by Quill at this time.
Note: Custom editing areas lose focus when using React 16 as a peer dep at this time (bug).
class MyComponent extends React.Component {
render() {
return (
<ReactQuill>
<div className="my-editing-area"/>
</ReactQuill>
);
}
});
Upgrading to ReactQuill v2 should be as simple as updating your dependency. However, it also removes support for long-deprecated props, the ReactQuill Mixin, and the Toolbar component.
Support for the toolbar, styles, pollInterval Quill options has long disabled. Starting from this release, ReactQuill will not warn you anymore if you try using them.
The ReactQuill Mixin allowed injecting the core functionality that made ReactQuill tick into your own components, and create deeply customized versions.
The Mixin has been considered an anti-pattern for a long time now, so we have decided to finalize its deprecation.
There is no upgrade path. If you have a use case that relied on the Mixin, you're encouraged to open an issue, and we will try to provide you with a new feature to make it possible, or dedicated support to migrate out of it.
Quill has long provided built-in support for custom toolbars, which replaced ReactQuill's (quite inflexible) Toolbar component.
Use the Toolbar Module or the HTML Toolbar feature instead.
// ES6
import ReactQuill, { Quill } from 'react-quill';
// CommonJS
const ReactQuill = require('react-quill');
const { Quill } = ReactQuill;
Quill
: The Quill namespace on which you can call register.
id
: ID to be applied to the DOM element.
className
: Classes to be applied to the DOM element.
value
: Value for the editor as a controlled component. Can be a string containing HTML, a Quill Delta instance, or a plain object representing a Delta.
Note that due to limitations in Quill, this is actually a semi-controlled mode, meaning that the edit is not prevented, but changing value will still replace the contents.
Also note that passing a Quill Delta here, and then an HTML string, or vice-versa, will always trigger a change, regardless of whether they represent the same document.
⚠️ Do not pass the delta object from the onChange event as value, as it will cause a loop. See Using Deltas for details.
defaultValue
: Initial value for the editor as an uncontrolled component. Can be a string containing HTML, a Quill Delta, or a plain object representing a Delta.
readOnly
: If true, the editor won't allow changing its contents. Wraps the Quill disable API.
placeholder
: The default value for the empty editor. Note: The Quill API does not support changing this value dynamically. Use refs and data-attributes instead (see #340).
modules
: An object specifying which modules are enabled, and their configuration. The editor toolbar is a commonly customized module. See the modules section over the Quill documentation for more information on what modules are available.
formats
: An array of formats to be enabled during editing. All implemented formats are enabled by default. See Formats for a list.
Custom formats should not be included in the array as of version 1.0.0. Instead they should be created through Parchment and registered with the module's Quill export.
style
: An object with custom CSS rules to apply on the editor's container. Rules should be in React's "camelCased" naming style.
theme
: The name of the theme to apply to the editor. Defaults to snow, Quill's standard theme. Pass null to use the minimal core theme. See the docs on themes for more information on including the required stylesheets.
tabIndex
: The order in which the editor becomes focused, among other controls in the page, during keyboard navigation.
bounds
: Selector or DOM element used by Quill to constrain position of popups. Defaults to document.body.
children
: A single React element that will be used as the editing area for Quill in place of the default, which is a <div>. Note that you cannot use a <textarea>, as it is not a supported target. Also note that updating children is costly, as it will cause the Quill editor to be recreated. Set the value prop if you want to control the html contents of the editor.
onChange(content, delta, source, editor)
: Called back with the new contents of the editor after change. It will be passed the HTML contents of the editor, a delta object expressing the change, the source of the change, and finally a read-only proxy to editor accessors such as getHTML().
⚠️ Do not use this delta object as value, as it will cause a loop. Use editor.getContents() instead. See Using Deltas for details.
onChangeSelection(range, source, editor)
: Called back with the new selected range, or null when unfocused. It will be passed the selection range, the source of the change, and finally a read-only proxy to editor accessors such as getBounds().
onFocus(range, source, editor)
: Called when the editor becomes focused. It will receive the new selection range.
onBlur(previousRange, source, editor)
: Called when the editor loses focus. It will receive the selection range it had right before losing focus.
onKeyPress(event)
: Called after a key has been pressed and released.
: Note that, like its native counterpart, this won't be called for special keys such as shift or enter. If you need those, hook onto onKeyDown or onKeyUp.
onKeyDown(event)
: Called after a key has been pressed, but before it is released.
: Note that, due to how Quill works, it's possible that you won't receive events for keys such as enter, backspace or delete. If that's the case, try hooking onto onKeyUp instead.
onKeyUp(event)
: Called after a key has been released.
preserveWhitespace
: If true, a pre tag is used for the editor area instead of the default div tag. This prevents Quill from
collapsing continuous whitespaces on paste. Related issue.
If you have a ref to a ReactQuill node, you will be able to invoke the following methods:
focus()
: Focuses the editor.
blur()
: Removes focus from the editor.
getEditor()
: Returns the Quill instance that backs the editor. While you can freely use this to access methods such as getText(), please avoid from imperatively manipulating the instance, to avoid getting ReactQuill and Quill out-of-sync. A much-safer unprivileged editor is available as replacement.
class Editor extends React.Component {
constructor(props) {
super(props);
this.quillRef = null; // Quill instance
this.reactQuillRef = null; // ReactQuill component
}
componentDidMount() {
this.attachQuillRefs();
}
componentDidUpdate() {
this.attachQuillRefs();
}
attachQuillRefs = () => {
if (typeof this.reactQuillRef.getEditor !== 'function') return;
this.quillRef = this.reactQuillRef.getEditor();
};
insertText = () => {
var range = this.quillRef.getSelection();
let position = range ? range.index : 0;
this.quillRef.insertText(position, 'Hello, World! ');
};
render() {
return (
<div>
<ReactQuill
ref={(el) => {
this.reactQuillRef = el;
}}
theme={'snow'}
/>
<button onClick={this.insertText}>Insert Text</button>
</div>
);
}
}
makeUnprivilegedEditor
: Creates an unprivileged editor. Pass this method a reference to the Quill instance from getEditor. Normally you do not need to use this method since the editor exposed to event handlers is already unprivileged.
const editor = this.reactQuillRef.getEditor();
const unprivilegedEditor = this.reactQuillRef.makeUnprivilegedEditor(editor);
// You may now use the unprivilegedEditor proxy methods
unprivilegedEditor.getText();
During events, ReactQuill will make a restricted subset of the Quill API available as the editor argument. This prevents access to destructive methods, which might cause ReactQuill to get out-of-sync with the component. It provides the following methods, which are mostly proxies of existing Quill methods:
getLength()
: Returns the length of the editor contents, in characters, not including any HTML tag.
getText()
: Returns the string contents of the editor, not including any HTML tag.
getHTML()
: Returns the full HTML contents of the editor.
getContents()
: Returns a Quill Delta of the complete document.
getSelection()
: Returns the current selection range, or null if the editor is unfocused.
getBounds()
: Returns the pixel position, relative to the editor container, and dimensions, of a selection, at a given location.
You can build libs, types and bundles:
npm build # or watch
You can also run the automated test suite:
npm test
More tasks are available as package scripts:
| Script | Description |
|---|---|
npm run build | Builds lib and browser bundle |
npm run watch | Rebuilds on source code changes |
npm run test | Runs unit tests and coverage |
npm run clean | Cleans build artifacts |
npm run demo | Serves a simple ReactQuill test application |
Please check the browser support table for the upstream Quill dependency. The ReactQuill distributable itself is ES5-compatible.
ReactQuill would not be where it is today without the contributions of many people, which we are incredibly grateful for:
The MIT License (MIT)
Copyright (c) 2020, zenoamaro [email protected]
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.