如何为react-draft-wysiwyg工具栏添加自定义按钮及用stateToHTML获取行内样式
react-draft-wysiwyg 工具栏扩展及样式导出解决方案

1. 文本对齐功能配置
原有代码中toolbar的options数组内textAlign缺少引号属于语法错误,先修正为字符串'textAlign'。react-draft-wysiwyg原生支持文本对齐能力,直接新增对齐配置即可:
toolbar={{ options: ['inline', 'blockType', 'list', 'emoji', 'textAlign'], // 新增对齐选项配置 textAlign: { options: ['left', 'center', 'right', 'justify'] } }}
配置后工具栏会自动出现左对齐、居中、右对齐、两端对齐四个选项。
2. 分隔线(水平线)功能实现
分隔线需要通过自定义工具栏按钮实现,步骤如下:
- 在toolbar的options数组中加入自定义按钮占位
- 实现插入分隔线的逻辑,调用Draft.js的Modifier接口修改块类型
- 配置自定义按钮的渲染和点击事件
实现代码示例:
// 插入分隔线处理函数 insertSeparator = () => { const { editorState } = this.state; const contentState = editorState.getCurrentContent(); const selectionState = editorState.getSelection(); const newContentState = Modifier.setBlockType( contentState, selectionState, 'horizontal-rule' ); const newEditorState = EditorState.push(editorState, newContentState, 'change-block-type'); this.handleEditorChange(newEditorState); } // Editor组件toolbar配置 toolbar={{ options: ['inline', 'blockType', 'list', 'emoji', 'textAlign', 'separator'], textAlign: { options: ['left', 'center', 'right', 'justify'] }, // 自定义按钮配置 customButtons: [ { key: 'separator', icon: '―', // 可替换为自定义图标 onClick: this.insertSeparator, title: '插入分隔线' } ] }}
3. 通过stateToHTML获取行内样式
需先安装draft-js-export-html依赖,默认导出即可自动转换内置行内样式为HTML标签及样式属性,如需适配自定义块/行内样式,可传入配置参数:
import { stateToHTML } from 'draft-js-export-html'; // 导出编辑器HTML内容 exportHtml = () => { const content = this.state.editorState.getCurrentContent(); const exportOptions = { // 处理自定义块样式,此处适配分隔线 blockStyleFn: (block) => { if (block.getType() === 'horizontal-rule') { return { start: '<hr />', end: '' }; } }, // 处理自定义行内样式,示例为自定义红色字体样式转换 inlineStyleFn: (styles) => { if (styles.has('RED_TEXT')) { return { style: { color: '#f00' } }; } } }; const html = stateToHTML(content, exportOptions); return html; }
导出的HTML字符串会自动包含文本对齐、字体粗细等所有行内样式。
4. 完整编辑器示例代码
<Editor editorState={this.state.editorState} onEditorStateChange={this.handleEditorChange} wrapperClassName="wrapper-class" editorClassName="editor-class" toolbarClassName="toolbar-class" toolbar={{ options: ['inline', 'blockType', 'list', 'emoji', 'textAlign', 'separator'], textAlign: { options: ['left', 'center', 'right', 'justify'] }, customButtons: [ { key: 'separator', icon: '―', onClick: this.insertSeparator, title: '插入分隔线' } ] }} />
内容的提问来源于stack exchange,提问作者CoderBeginner
相关产品推荐
相关产品推荐

