用react实现一个评论功能

175 阅读1分钟
import { useRef, useState } from 'react'
import _ from 'lodash' // 安装并导入lodash库 
import classnames from 'classnames' //安装并导入classnames库 
import { v4 as uuidV4 } from 'uuid'
import dayjs from 'dayjs'

const App = () => { 
    const [commentList,setCommentList]=useState(_.orderBy(list,'like','desc'));//orderBy是lodash的方法,参数第一个是变量名称,第二个是按照什么字段排序,第三个是升序还是降序 
    const handleTabChange = (type) => { 
        setType(type) 
        if(type == 'hot') { 
            //根据点赞数量排序 
            //lodash 一个js库,有很多功能 
            setCommentList(_.orderBy(commentList,'like','desc')) 
        }else { 
            //根据创建时间排序 
            setCommentList(_.orderBy(commentList,'ctime','desc')) 
        } 
   }
   const [content, setContent] = useState('')
   const inputRef = useRef(null)
   setCommentList([
      ...commentList,
      {
        rpid: uuidV4(), //随机数id 用uuid库
        user: {
          uid: '30009257',
          avatar:avatar,
          uname: '黑马前端',
        },
        content: content,
        ctime: dayjs(new Date()).format('MM-DD HH:mm'), //格式化 月-日 时-分  用Day.js包
        like: 66,
      }
    ])
    // 1、清空输入框内容
    setContent('')
    // 2、重新聚焦  用useRef获取dom元素 ,调用focus方法
    inputRef.current.focus()
  }
   return ( 
       <div className="app">
           //发表评论,点击发布后
           <textarea
              className="reply-box-textarea"
              placeholder="发一条友善的评论"
              ref={inputRef}
              value={content}
              onChange={(e) => setContent(e.target.value)}
            />
            <div className="reply-box-send">
              <div className="send-text" onClick={handlePublish}>发布</div>
            </div>
           //切换tab
           <ul> 
           {tabs.map(item => 
               <span key={item.type} 
               onClick={() => handleTabChange(item.type)} 
               className={`nav-item ${type === item.type && 'active'}`}> 
               {item.tabName} 
               </span>
           )} 
           //如果用classnames插件就写成,classnames方法里面第一个参数是静态class名,第二个参数是动态class,key是active即动态的class名称,value是条件: 
               //className={classnames('nav-item',{active:type === item.type})} 
           </ul> 
       </div>
 )}