【React】tab切换功能和排序实现,classnames工具优化类名控制
目录
一、渲染Tab+点击高亮实现
二、排序功能实现
三、classnames工具优化类名控制
一、渲染Tab+点击高亮实现
需求:点击哪个tab项,哪个做高亮处理
核心思路:点击谁就把谁的Type(独一无二的标识)记录下来,然后和遍历时的每一项type做匹配,谁匹配到就设置负责高亮的类名
//tab切换功能//1.点击谁就把谁的Type(独一无二的标识)记录下来//2.通过记录的type和每一项遍历时的type做匹配,控制激活类名的显示const [type, setType] = useState("hot");const handleTabChange = (type) => {console.log(type);setType(type);};
{/* 高亮类名: active */}{tabs.map((item) => (<spankey={item.type}onClick={() => handleTabChange(item.type)}className={`nav-item ${type === item.type && "active"}`}>{item.text}</span>))}
二、排序功能实现
需求:
点击最新,评论列表按照创建时间倒序排列(新的在前),点击最热按照点赞数排序(多的在前)
核心思路:
把评论列表状态数据进行不同的排序处理,当成新值传给set函数重新渲染视图UI
lodash库:
npm i lodash
导入:import _ from "lodash";
const [type, setType] = useState("hot");const handleTabChange = (type) => {console.log(type);setType(type);//基于列表的排序//lodashif (type === "hot") {//根据点赞数进行排序setCommentList(_.orderBy(commentList, "like", "desc"));} else {//根据时间进行排序setCommentList(_.orderBy(commentList, "ctime", "desc"));}};
但是这段代码只有当你点击最热或者最新时候才会排序,我们还需要设置初始化就排序好的列表
const App = () => {
const [commentList, setCommentList] = useState(
_.orderBy(defaultList, "like", "desc")
);
三、classnames工具优化类名控制
classnames是一个简单的JS库,可以非常方便的通过条件动态控制class类名的显示
问题:字符串的拼接方法不够直观,也容易出错
classnames库:
npm install classnames