React中useRef实现textarea剩余字符计数及输入限制问题
问题解决:Textarea剩余字符数显示与输入限制
报错原因
你初始化useRef时传了0,组件首次渲染时cntCharLeft.current是数值0,并非绑定的textarea DOM元素,此时访问cntCharLeft.current.value.length必然触发报错。
解决方案
1. 修正Ref用法(原生DOM方式)
先将ref初始化为null,同时添加空值判断避免首次渲染报错,再实现输入限制逻辑:
import { useRef } from 'react'; // ... const cntCharLeft = useRef(null); // 初始化为null,用于绑定DOM元素 const MAX_LENGTH = 250; const submitHandler = (e) => { e.preventDefault(); // 处理表单提交逻辑 }; const handleTextareaChange = () => { const currentValue = cntCharLeft.current.value; // 超过最大长度则截断内容 if (currentValue.length > MAX_LENGTH) { cntCharLeft.current.value = currentValue.slice(0, MAX_LENGTH); } }; return ( <Card className={styles.content} > <form onSubmit={submitHandler}> <textarea rows='6' ref={cntCharLeft} onChange={handleTextareaChange} /> {/* 用可选链处理current可能为null的情况,默认长度为0 */} <p className={styles.charsLeft} > {MAX_LENGTH - (cntCharLeft.current?.value.length || 0)} characters left </p> <Button type='submit'>Enter</Button> </form> </Card> );
2. 更推荐的React状态管理方式
用useState跟踪输入内容,状态变化会自动触发组件重渲染,更贴合React数据流模式:
import { useState } from 'react'; // ... const MAX_LENGTH = 250; const [inputValue, setInputValue] = useState(''); const submitHandler = (e) => { e.preventDefault(); // 提交时直接使用inputValue即可 }; const handleTextareaChange = (e) => { const currentValue = e.target.value; // 未超过长度才更新状态,自动限制输入 if (currentValue.length <= MAX_LENGTH) { setInputValue(currentValue); } }; return ( <Card className={styles.content} > <form onSubmit={submitHandler}> <textarea rows='6' value={inputValue} onChange={handleTextareaChange} maxLength={MAX_LENGTH} {/* 可配合原生属性双重限制 */} /> <p className={styles.charsLeft} > {MAX_LENGTH - inputValue.length} characters left </p> <Button type='submit'>Enter</Button> </form> </Card> );
额外提示
- 可以直接给textarea添加
maxLength={250}原生属性,浏览器会自动阻止超过长度的输入,无需手动编写截断逻辑。 - 使用
useState的方式更易维护,后续若需基于输入内容做表单验证、实时提示等逻辑,扩展起来更方便。
内容的提问来源于stack exchange,提问作者D. Rattansingh
相关产品推荐
相关产品推荐

