我有以下代码用于将注释添加到表中
const [newComment, setNewComment] = useState('')
<textarea onChange={e => setNewComment(e.target.value)} placeholder='Add a comment'/>
<button onClick={() => AddComment(newComment)}>Add</button>
单击按钮添加注释后,我希望文本区域值清除/重置为原始占位符"添加注释"。目前,在我按下按钮后,注释会被添加,但文本区域会保留"newComment";值意味着我必须手动清除它,然后才能插入一个不太方便的新评论-有什么建议吗?
它应该可以工作。按下按钮后,将值设置为空字符串
const [newComment, setNewComment] = useState('')
<input value={newComment} onChange={e => setNewComment(e.target.value)} placeholder='Add a comment'/>
<button onClick={() => {
AddComment(newComment)
setNewComment('')
}}>Add</button>
我认为您希望将文本区域设置为React所称的"受控部件";通过给它一个反映newComment
状态的value
属性:
const [newComment, setNewComment] = useState("");
return (
<div>
<textarea
onChange={e => setNewComment(e.target.value)}
placeholder="Add a comment"
value={newComment}
/>
<button
onClick={() => {
AddComment(newComment)
setNewComment("");
}}
>
Add
</button>
</div>
);