0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

4-React 受控表单绑定 react中获取dom

Posted at

一:受控表单绑定

image.png
通过react状态去控制Input框的状态
image.png

二:react中获取dom

在react中获取dom元素:
1.useRef生成ref对象,绑定到想获取的dom标签身上
2.dom可用时,ref.current获取dom
image.png
image.png

三:案例--发表评论

1.核心功能实现

①用数控绑定方式,可以把用户输入的东西,收集到content里面
②点击时发布评论,替换content字段,收集到的数据是什么就绑定什么
③延续数据修改不可变的方式,原本的所有数据都展开,增加一条自己的数据
image.png

// 发表评论
const [content,setContent] = useState("")
const handPublish =()=>{
  setCommentList([
      ...commentList,
      {
         rpid:100,
         user:{
            uid:"30009257",
            avatar,
            uname:"黑马前端",
         },
         content:content,
         ctime:"10-19 09:00",
         like:66,
         }
  ])
}
// 评论框
<textarea
    className="reply-box-textarea"
    placeholder="发一条友善的评论"
    value={content}
    onChange={(e)=>setContent(e.target.value)}
/>
// 发布按钮
<div className="reply-box-send">
   <div className="send-text" onClick={handPublish}>发布</div>
</div>

2.id和时间处理

image.png
1.①安装uuid

npm install uuid

②使用方式
image.png
2.Day.js
1.①安装

npm install dayjs

②使用方式
image.png

{
import {v4 as uuidV4} from "uuid"
import dayjs from "dayjs"
         rpid:uuidV4(), //随机id
         user:{
            uid:"30009257",
            avatar,
            uname:"黑马前端",
         },
         content:content,
         ctime:dayjs(new Date()).format("MM-DD hh:mm"),// 格式化 月-日 时:分
         like:66,
         }

3.清空内容和聚焦实现

image.png

// 1.清空输入框内容
setContent("")
// 2.重新聚焦 dom(useRef) -focus
const inputRef = useRef(null)
inputRef.current.focus()
// 评论框
<textarea
    className="reply-box-textarea"
    placeholder="发一条友善的评论"
    ref={inputRef}
    value={content}
    onChange={(e)=>setContent(e.target.value)}
/>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?