You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

react-draft-wysiwyg富文本编辑器输入时文字溢出问题如何解决?

问题复现

问题截图
你当前的实现代码如下:

import React, {Component } from "react";
import { Editor } from "react-draft-wysiwyg";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import { EditorState } from "draft-js";

class CreatePostPage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      editorState: EditorState.createEmpty()
    }
  }

  onEditorStateChange = (editorState) => {
    this.setState({
      editorState
    })
  }

  render() {
    const { editorState } = this.state;
    return (
      <div
        className="rounded"
        style={{
          marginTop: 100,
          marginLeft: 50,
          marginRight: 50,
          backgroundColor: "white",
          height: "35rem",
        }}
      >
        <Editor
          editorState={editorState}
          toolbarClassName="toolbarClassName"
          wrapperClassName="wrapperClassName"
          editorClassName="editorClassName"
          onEditorStateChange={this.onEditorStateChange}
        />
      </div>
    );
  }
}

export default CreatePostPage;
解决方案

出现文字溢出的核心原因是你给外层容器设置了固定高度35rem,但react-draft-wysiwyg的编辑器内容区域默认没有配置超出滚动规则,内容超过容器高度时就会溢出容器范围,可通过以下任意一种方法解决:

方法1:自定义编辑器类名样式

你在Editor组件中已经配置了editorClassName="editorClassName",直接在全局样式文件或者当前组件的样式中添加如下规则即可:

.editorClassName {
  /* 内容超出时自动出现纵向滚动条 */
  overflow-y: auto;
  /* 最大高度设置为外层容器高度减去工具栏高度(工具栏高度约3rem,可根据实际调整) */
  max-height: 32rem;
  /* 强制长文本/长单词换行,避免横向溢出 */
  word-break: break-all;
}

方法2:直接配置Editor组件的行内样式

如果不想单独写样式文件,可以直接给Editor组件添加editorStyle属性,直接传入样式配置:
修改你的Editor组件代码如下:

<Editor
  editorState={editorState}
  toolbarClassName="toolbarClassName"
  wrapperClassName="wrapperClassName"
  editorClassName="editorClassName"
  onEditorStateChange={this.onEditorStateChange}
  // 新增以下行内样式配置
  editorStyle={{
    overflowY: 'auto',
    maxHeight: '32rem',
    wordBreak: 'break-all'
  }}
/>

适配优化(可选)

如果需要让编辑器整体完全适配外层容器的固定高度,不需要手动计算内容区高度,可以用弹性布局适配:

  1. 给外层容器添加overflow: hidden样式
  2. 添加如下样式规则:
.wrapperClassName {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.editorClassName {
  flex: 1;
  overflow-y: auto;
  word-break: break-all;
}

内容的提问来源于stack exchange,提问作者gurkan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 22:24:04