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

如何让React Input随内容溢出自动增高?基于Tailwind CSS的实现求助

实现React Input(多行自适应高度)类似Discord输入框

核心思路

原生<input>标签是单行结构,无法实现自动换行增高,所以必须让你的Input组件底层渲染<textarea>标签(如果用第三方UI库的Input,通常会提供多行版本,比如Input.TextArea)。结合Tailwind CSS样式和React的事件监听、状态控制,就能实现高度随内容自动适配的效果。

具体实现步骤

1. 自定义自适应高度Input组件(基于textarea)

如果是你自己封装的Input组件,直接替换为textarea并添加高度调整逻辑:

import { useState, useRef, useEffect } from 'react';

const AutoResizeInput = ({ placeholder, className, ...props }) => {
  const [height, setHeight] = useState('auto');
  const textareaRef = useRef(null);

  // 初始化时设置初始高度
  useEffect(() => {
    if (textareaRef.current) {
      setHeight(`${textareaRef.current.scrollHeight}px`);
    }
  }, []);

  // 输入时动态调整高度
  const handleInput = () => {
    if (textareaRef.current) {
      // 先重置为auto,保证scrollHeight计算准确
      textareaRef.current.style.height = 'auto';
      setHeight(`${textareaRef.current.scrollHeight}px`);
    }
  };

  return (
    <textarea
      ref={textareaRef}
      style={{ height }}
      onInput={handleInput}
      placeholder={placeholder}
      className={`min-h-[44px] w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none ${className}`}
      {...props}
    />
  );
};

// 组件使用示例
export default function App() {
  return (
    <div className="w-1/2 mx-auto mt-10">
      <AutoResizeInput placeholder="输入消息..." />
    </div>
  );
}

2. Tailwind样式说明

  • min-h-[44px]:设置输入框最小高度,和Discord初始输入框高度对齐
  • resize-none:禁止用户手动拖拽调整输入框大小
  • w-full:让输入框宽度铺满父容器
  • 边框、圆角、聚焦状态样式可根据你的设计需求调整

3. 第三方UI库适配(以Ant Design为例)

如果项目用了第三方UI库的Input组件,比如Ant Design的Input,直接使用其多行版本Input.TextArea并添加相同的高度调整逻辑:

import { useState, useRef } from 'react';
import { Input } from 'antd';

const AutoResizeAntInput = () => {
  const [height, setHeight] = useState(44);
  const textareaRef = useRef(null);

  const handleInput = () => {
    if (textareaRef.current) {
      textareaRef.current.style.height = 'auto';
      setHeight(textareaRef.current.scrollHeight);
    }
  };

  return (
    <Input.TextArea
      ref={textareaRef}
      style={{ height, minHeight: 44, resize: 'none' }}
      onInput={handleInput}
      placeholder="输入消息..."
      className="px-4 py-2 rounded-lg"
    />
  );
};

关键注意事项

  • 必须基于<textarea>实现,原生<input>不支持多行自适应高度
  • 每次输入时先重置高度为auto,再获取scrollHeight,避免计算偏差
  • 设置min-height防止内容清空后输入框变得过矮

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 19:40:29