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?

3-React案例

Posted at

image.png

一:列表渲染:map方法

只要数据会影响到视图的变化,都应该用useState去做维护
通过useState传过来假数据,做渲染
image.png

// 渲染评论列表
// 1.使用useState维护评论列表list
const[commentList,setCommentList]=useState(list)
// 2.遍历渲染评论项
{commentList.map(item=> (
   <div key={item.rpid}>评论项</div>
))}
// 3.修饰细节 头像 用户名 评论内容 评论时间 评论数量
{item.user.avatar}
{item.user.uname}
{item.content}
{item.ctime}
{item.like}

二:删除功能实现

1.条件渲染:是否是自己的评论
2.通过id去做匹配,过滤
image.png
怎样确定是自己的评论:user中有一个uid 代表当前用户的Id
评论列表中每一项有一个user uid,两个uid一致则认为是自己的评论
filter函数返回一个新数组,不更改老数组
filter:类似于一个漏斗,满足条件的留下,不满足条件的漏下去
比如:一共有五条评论,id分别为12345,用户id和评论区id都为3,那么就把3漏下去,把1245作为一个新的数组返回

// 条件:user.id=== item.user.id
// 删除功能
const handleDel = (id)=>{
  console.log(id)
  // 对commentList做过滤处理
  setCommentList(commentList.filter(item=> item.rpid !== id ))
}
{user.uid=== item.user.uid && 
  <span className="delete-btn" onClick={()=> handleDel(item.rpid)}>
  删除
  </span>}

条件控制删除按钮的显示,用户的id和评论项的id去做匹配,匹配上就显示
删除功能是通用的功能:拿到当前项id,以id作为条件去做过滤

三:tab切换功能实现

tab切换类功能点击高亮实现通用功能
image.png

// tab切换功能
// 1.点击谁就把谁的type记录下来
// 2.通过记录的type和每一项遍历时的type做匹配,控制激活类名的显示
const [type,setType] = useState("hot")
const handleTabChange =(type) =>{
  console.log(type)
  setType(type)
}
const tabs = [
    {type:"hot",text:"最热"},
    {type:"time",text:"最新"},
]
// 高亮类名 active
{tabs.map(item=> 
    <span 
       key={item.type} 
       onClick={()=>handleTabChange(item.type)} 
       className={"nav-item ${type === item.type && "active"}"}>
       {item.text}
    </span>)}

四:排序实现

image.png
lodash:封装好了很多个工具方法的函数库
order by:快速给数据做排序 生成一份全新的数据,不会更改老数据
image.png
安装lodash命令

npm i --save lodash
// 导入lodash
import _ from "lodash"
const [type,setType] = useState("hot")
const handleTabChange =(type) =>{
  console.log(type)
  setType(type)
  // 初始值
  const[commentList,setCommentList]=useState(_.orderBy(list,"like","desc"))
  // 基于列表的排序
  if(type === "hot"){
   // 根据点赞数排序
   setCommentList(_.orderBy(commentList,"like","desc"))
  }else{
   // 根据创建时间排序
   setCommentList(_.orderBy(commentList,"ctime","desc"))
  }
}

五:classnames优化类名控制

image.png
安装方式

npm install classnames
import classNames from "classnames"
 className={classNames("nav-item",{active:type === item.type})}
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?