「我的学习笔记」React基础day02(基于黑马程序员b站评论区案例整理)

列表渲染

利用useState维护list
创建一个useState

const [commentList, setCommentlist] = useState(list)

调动静态数据

{
    
    commentList.map(item => (
            <div key={
    
    item.rpid} className="reply-item">
            //后面省略掉啦……太长了

实现删除功能

需求:
1.只有自己的评论才能删除
2.点击删除按钮,删除当前评论,列表不再展示

核心思路

1.删除显示-条件渲染
2.删除功能-拿到当前id以id为条件对评论列表做filter过滤

显示条件:user.id ===item.user.id

{
    
    user.uid === item.user.uid && <span className="delete-btn" onClick={
    
    () => 
handleDel(item.rpid)}>删除</span>}

声明回掉函数

const handleDel = (id) => {
    
    
    console.log(id)
    //对commentlist做过滤处理
    setCommentlist(commentList.filter(item => item.rpid !== id))
  }

实现tab切换交互

需求:点击哪个tab项,哪个就做高亮处理

核心思路

点击谁就把谁的type记录下来,然后和遍历的每一项type做匹配,谁匹配到谁就负责高亮的类名

创建tab数组

const tabs = [
  {
    
     type: 'hot', text: '最热' },
  {
    
     type: 'time', text: '最新' },
]

引入classnames包

npm install classname

import 一下classname

import className from 'classnames'

渲染tab的值并把当前的值调出去

{
    
    tabs.map(item =>
              <span key={
    
    item.type}
                onClick={
    
    () => handleTabChange(item.type)}
                className = {
    
    className('nav-item',{
    
    active:type===item.type})}>
                {
    
    item.text}
              </span>)}
              //实现高亮

写个回调函数

const handleTabChange = (type) => {
    
    
    console.log(type)
    }

现在就是点谁返回谁啦!

创建一个useState设置默认值为hot

 const [type, setType] = useState('hot')

在这里插入图片描述
通过React Devolver Tool 可以看到我们的代码已经成功实现效果了,在点击的时候我们确实把值存到state中了!

排序功能的实现

需求:

1、点击最新,评论列表按照最新的倒序排列。
2、点击最热,按照点赞数量排列。

核心思路

把评论列表的状态数据进行不同的排序处理,当成新的值给set函数,重现渲染。

引入lodash

npm install lodash

调用lodash库

import _ from 'lodash'

写一个if函数实现功能

const handleTabChange = (type) => {
    
    
    console.log(type)
    setType(type)
    if(type==='hot'){
    
    
      setCommentlist(_.orderBy(commentList,'like','desc'))
    }else{
    
    
      setCommentlist(_.orderBy(commentList,'ctime','desc'))
    }
  }

修改默认排序方式

  const [commentList, setCommentlist] = useState(_.orderBy(list,'like','desc'))

总结

今天通过b站评论区的案例巩固了usestate的用法,以及学习了lodash库的调用和classname库的调用,学会了通过工具快速排序,以及更加简洁的改变classname的方法。

猜你喜欢

转载自blog.csdn.net/weixin_69464412/article/details/135230815