React组件点击LOG按钮获取textarea值异常问题求助
问题描述
React代码运行不稳定,仅偶尔能捕获textarea的值,多数时候无法成功。尝试过onBlur、onBlurCapture、onChange、onChangeCapture等事件,均无改善。需要实现获取textarea的值并追加到logList中。
相关代码
function Paste() { const Log = "LOG"; const [logList, setLogList] = useState([{ text: "Yes", id: 1 }]); const [newLogValue, setNewLogValue] = useState(0); const appendToList = () => { alert(newLogValue); const newLogList = [ ...logList, { text: newLogValue, id: logList.length + 1 }, ]; setLogList(newLogList); }; return ( <> <textarea style={{ width: "24%", height: "80%", display: "block", marginLeft: "3%", verticalAlign: "top", border: "3px solid #F08080", background: "#808080", }} onChange={(e) => setNewLogValue(e.target.value)} ></textarea> <button style={{ width: "24.3%", height: "10%", display: "block", float: "left", marginLeft: "3%", }} value={Log} > <p style={{ FontFace: "Mono", fontWeight: "bold", fontSize: "14px" }} onClick={appendToList} > LOG </p> </button> <List logList={logList}></List> </> ); }
解决方案
- 修正状态初始值:
newLogValue初始设为数字0,但textarea输入的是字符串,类型不匹配可能导致异常,改成空字符串""。 - 优化状态更新逻辑:更新
logList时用函数式更新,避免闭包导致的旧状态引用问题,确保每次都拿到最新的logList。 - 调整事件绑定位置:把
onClick直接绑定在button上,而非内部的p标签,避免事件冒泡或触发异常的问题。 - 修正样式属性拼写:原代码中
FontFace是错误写法,改为标准的fontFamily。
修改后的代码:
function Paste() { const Log = "LOG"; const [logList, setLogList] = useState([{ text: "Yes", id: 1 }]); const [newLogValue, setNewLogValue] = useState(""); const appendToList = () => { setLogList(prevList => [ ...prevList, { text: newLogValue, id: prevList.length + 1 } ]); // 可选:追加后清空textarea setNewLogValue(""); }; return ( <> <textarea style={{ width: "24%", height: "80%", display: "block", marginLeft: "3%", verticalAlign: "top", border: "3px solid #F08080", background: "#808080", }} value={newLogValue} onChange={(e) => setNewLogValue(e.target.value)} ></textarea> <button style={{ width: "24.3%", height: "10%", display: "block", float: "left", marginLeft: "3%", }} onClick={appendToList} > <p style={{ fontFamily: "Mono", fontWeight: "bold", fontSize: "14px" }} > LOG </p> </button> <List logList={logList}></List> </> ); }
内容的提问来源于stack exchange,提问作者user204069
相关产品推荐
相关产品推荐

