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

Next.js13自定义textarea组件添加事件监听报错求解

解决Next.js 13自定义Textarea自动调整高度的事件绑定问题

错误原因

你写的textarea是React生成的虚拟DOM对象,不是浏览器实际渲染的真实DOM元素,虚拟DOM没有addEventListener方法,这就是报错的核心原因。

两种可行解决方案

方案1:使用useRef获取真实DOM(推荐,适合需要手动管理事件的场景)

通过useRef关联真实DOM节点,在组件挂载后添加事件监听器,卸载时移除,确保只作用于当前组件的textarea:

import { useRef, useEffect } from 'react';
import styles from './YourComponent.module.css'; // 替换为你的样式文件路径

const CustomTextarea = ({ id, fieldProps }) => {
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  useEffect(() => {
    const handleInput = () => {
      if (!textareaRef.current) return;
      // 先重置高度为auto,再根据滚动高度计算新高度
      textareaRef.current.style.height = 'auto';
      textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`;
    };

    const textareaElement = textareaRef.current;
    if (textareaElement) {
      textareaElement.addEventListener('input', handleInput);
      // 组件卸载时移除监听器,避免内存泄漏
      return () => textareaElement.removeEventListener('input', handleInput);
    }
  }, []);

  return (
    <textarea
      ref={textareaRef}
      id={id}
      className={styles.input}
      {...fieldProps}
    />
  );
};

export default CustomTextarea;

方案2:直接绑定React的onInput事件(更简洁)

利用React内置的事件绑定语法,直接把处理函数挂到当前textarea上,自动避免影响其他组件:

import styles from './YourComponent.module.css';

const CustomTextarea = ({ id, fieldProps }) => {
  const handleInput = (e: React.FormEvent<HTMLTextAreaElement>) => {
    const textarea = e.currentTarget;
    textarea.style.height = 'auto';
    textarea.style.height = `${textarea.scrollHeight}px`;
    // 如果用户传入了自定义onInput,需执行它
    if (fieldProps.onInput) {
      fieldProps.onInput(e);
    }
  };

  return (
    <textarea
      id={id}
      className={styles.input}
      onInput={handleInput}
      {...fieldProps}
    />
  );
};

export default CustomTextarea;

补充说明

  • 两种方案都不需要依赖id,完全符合你的约束条件
  • 方案2中如果用户传入了onInput,记得在自定义处理函数中调用它,避免覆盖用户的自定义逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 06:52:47