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

如何在加载时自动调整textarea高度,适配预填充的回显内容?

问题原因

你遇到的问题本质是高度调整逻辑的触发时机缺失:你现有的高度计算逻辑只绑定了输入相关事件(比如keydown、input),但组件挂载、value属性更新(回显数据时)的场景没有触发高度重算,同时如果计算前没有重置高度,还会出现scrollHeight计算为旧值的问题。

修复方案

1. 抽离公共高度调整函数

先把高度调整逻辑封装为独立方法,确保所有场景调用的逻辑一致:

function adjustTextareaHeight(textareaEl) {
  // 先重置高度为auto,让浏览器重新计算内容实际高度
  textareaEl.style.height = 'auto';
  // 加上少量偏移量避免最后一行内容被裁切
  textareaEl.style.height = `${textareaEl.scrollHeight + 2}px`;
}

注意:需要给textarea设置box-sizing: border-box,避免padding、border导致高度计算偏差

2. 补充触发时机

除了原有的输入事件触发外,额外在以下两个场景调用调整函数:

原生JS场景

页面加载完成、textarea赋值后调用:

window.addEventListener('load', () => {
  const textarea = document.querySelector('#your-textarea-id');
  // 赋值后调用
  textarea.value = '从数据库读取的回显文本';
  adjustTextareaHeight(textarea);
})

Vue 场景

用watch监听绑定的value,配合nextTick确保DOM更新完成后再计算:

const props = defineProps(['value'])
const textareaRef = ref()

watch(
  () => props.value,
  () => {
    nextTick(() => {
      adjustTextareaHeight(textareaRef.value)
    })
  },
  // 开启immediate,组件挂载时就触发第一次计算
  { immediate: true }
)

React 场景

在useEffect中添加value为依赖项,初始挂载和value更新时都会触发:

const TextareaAutoHeight = ({ value }) => {
  const textareaRef = useRef(null)

  useEffect(() => {
    if (!textareaRef.current) return
    adjustTextareaHeight(textareaRef.current)
  }, [value]) // 依赖项添加value,每次value变化都重算

  return <textarea ref={textareaRef} value={value} />
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 01:54:08