如何移除react-draft-wysiwyg自动添加的<p>标签?
移除react-draft-wysiwyg自动添加的
标签
react-draft-wysiwyg基于Draft.js实现,默认会将输入内容包裹在<p>标签中,你可以通过以下两种方式解决这个问题:
方法一:修改编辑器默认块类型,避免生成
标签
Draft.js默认的空编辑器块类型是unstyled,但react-draft-wysiwyg在交互时可能自动切换为paragraph。你可以初始化编辑器时指定unstyled块,并自定义块渲染逻辑:
- 初始化带有
unstyled块的EditorState:
import { EditorState, ContentState, ContentBlock } from 'draft-js'; // 创建初始内容,使用unstyled块而非paragraph const initialContent = ContentState.createFromBlockArray([ new ContentBlock({ key: 'initial-block', type: 'unstyled', text: '', }), ]); const [questionState, setQuestionState] = useState<EditorState>( EditorState.createWithContent(initialContent) );
- 自定义块渲染函数,将paragraph块替换为无标签容器:
const blockRenderer = (contentBlock) => { const blockType = contentBlock.getType(); if (blockType === 'paragraph') { return { component: 'div', props: { style: { margin: '0' } }, // 清除默认段落边距 }; } // 其他块类型保持默认渲染 return null; };
- 在Editor组件中传入自定义渲染函数:
<Editor editorState={questionState} onEditorStateChange={setQuestionState} editorClassName='editor' toolbarClassName='toolbar' wrapperClassName='wrapper' ariaLabel='question' editorProps={{ blockRendererFn: blockRenderer }} />
方法二:导出内容时过滤
标签
如果不需要修改编辑器内部渲染,仅在获取最终HTML时移除<p>标签,可以使用draft-js-export-html库自定义转换规则:
- 安装依赖:
npm install draft-js-export-html
- 转换内容时跳过
标签的包裹:
import { stateToHTML } from 'draft-js-export-html'; // 将EditorState转换为HTML,移除paragraph块的<p>标签 const getCleanHTML = () => { return stateToHTML(questionState.getCurrentContent(), { blockRenderers: { paragraph: () => ({ start: '', end: '' }), }, }); };
内容的提问来源于stack exchange,提问作者xFlame
相关产品推荐
相关产品推荐

