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

React实现文本输入框自适应高度+屏幕居中自动滚动方案咨询

React实现自适应高度+自动滚动的文本编辑器

一、基础环境配置

先安装React-Quill依赖:

npm install react-quill quill

二、核心组件实现

下面是完整的组件代码,集成了自适应高度和自动滚动功能:

import React, { useRef, useEffect } from 'react';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import { debounce } from 'lodash'; // 可选,用于防抖优化

const AutoScrollEditor = () => {
  const quillRef = useRef(null);
  const editorContainerRef = useRef(null);

  // Quill工具栏配置
  const modules = {
    toolbar: [
      ['bold', 'italic', 'underline'],
      ['link'],
      [{ 'list': 'ordered'}, { 'list': 'bullet' }]
    ],
  };

  // 监听内容变化,自适应编辑器高度
  useEffect(() => {
    const quill = quillRef.current?.getEditor();
    if (!quill) return;

    const adjustHeight = () => {
      const contentHeight = quill.root.scrollHeight;
      editorContainerRef.current.style.height = `${contentHeight + 20}px`;
    };

    quill.on('text-change', adjustHeight);
    adjustHeight(); // 初始化时设置高度

    return () => quill.off('text-change', adjustHeight);
  }, []);

  // 监听光标位置,自动滚动到屏幕中心
  useEffect(() => {
    const quill = quillRef.current?.getEditor();
    if (!quill) return;

    const scrollToCursor = debounce((range) => {
      if (!range || range.length !== 0) return;
      const [leaf] = quill.getLeaf(range.index);
      const domNode = leaf.domNode;
      const rect = domNode.getBoundingClientRect();
      const screenCenterY = window.innerHeight / 2;
      const targetScrollY = window.scrollY + rect.top - screenCenterY + rect.height / 2;

      window.scrollTo({
        top: targetScrollY,
        behavior: 'smooth'
      });
    }, 80); // 防抖延迟,避免频繁滚动

    quill.on('selection-change', scrollToCursor);

    return () => quill.off('selection-change', scrollToCursor);
  }, []);

  return (
    <div ref={editorContainerRef} style={{ border: '2px solid red', margin: '20px auto', width: '80%', minHeight: '100px' }}>
      <ReactQuill
        ref={quillRef}
        modules={modules}
        theme="snow"
        style={{ border: '2px solid blue', height: '100%' }}
      />
    </div>
  );
};

export default AutoScrollEditor;

三、关键CSS补充

为了让Quill编辑器能正确撑开高度,添加以下全局CSS:

.ql-container {
  height: auto !important;
  font-size: 16px;
}
.ql-editor {
  min-height: 80px;
  padding: 12px;
}

四、功能说明

  • 自适应高度:通过监听text-change事件,获取编辑器内容的实际滚动高度,动态设置容器高度,确保编辑器始终包裹全部内容
  • 自动滚动定位:监听selection-change事件,获取光标所在的DOM节点,计算其相对于屏幕中心的位置,调用window.scrollTo实现平滑滚动,让光标始终保持在屏幕中心附近
  • 防抖优化:用防抖函数减少滚动触发频率,避免输入时的滚动抖动

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 05:05:24