import React, {useRef, useState} from "react";
const CommentForm = ({onAddComment}) => {
const [newCommentText, setNewCommentText] = useState('');
const textRef = useRef(null);
const handleAddComment = () => {
if (newCommentText.trim() !== '') {
onAddComment(newCommentText);
setNewCommentText('');
textRef.current.focus();
}
};
return (
<div>
<input
type="text"
ref={textRef}
value={newCommentText}
onChange={(e) => setNewCommentText(e.target.value)}
placeholder="输入你的评论"
/>
<button onClick={handleAddComment}>提交评论</button>
</div>
);
};
10 React控件双向绑定和Ref使用
最新推荐文章于 2024-09-18 14:42:57 发布