前言:这篇文章中的代码并不是单单在React中使用。我现在用React写的。
先上效果图
本片文章的效果示范
第一步定义数据结构:
const [list, setList] = useState([
// domeDone 表示该数据的状态
{ name: '匿名用户', rate: 4.5, domeDone: 0 },
{ name: '匿名用户', rate: 5, domeDone: 0 },
{ name: '蛇', rate: 3, domeDone: 0 },
{ name: '匿名用户', rate: 2, domeDone: 3 },
{ name: '匿名用户', rate: 5, domeDone: 0 },
{ name: '匿名用户', rate: 3, domeDone: 0 },
{ name: '熊', rate: 2, domeDone: 3 },
{ name: '匿名用户', rate: 5, domeDone: 2 },
{ name: '长鼻猴', rate: 3, domeDone: 1 },
{ name: '妮数', rate: 2, domeDone: 3 },
])
第二步定义一个默认值
// 用来控制显示数据
const [type, setType] = useState(undefined)
第三步就是定义一行按钮,用来展示该类型的值
// 这种写法是在react和umi中的代码规格写法
<span style={type === undefined ? { background: "red" } : {}} onClick={() => { setType(undefined) }}>全部</span>
<span style={type === 1 ? { background: "red" } : {}} onClick={() => { setType(1) }}>最新</span>
<span style={type === 2 ? { background: "red" } : {}} onClick={() => { setType(2) }}>好评</span>
<span style={type === 3 ? { background: "red" } : {}} onClick={() => { setType(3) }}>差评</span>
第四步就是数据的切割以及数据的展示
var sliceList = type === undefined ? list : list.filter(item => item.domeDone === type)
<div>
{sliceList.map((item, index) => (
<div className='main-box' key={index}>
<div style={{ float: 'left', width: '30%' }}>
<img src={item.img} />
</div>
<div style={{ float: 'right', width: '70%' }}>
div>{item.name}</div>
</div>
</div>
))}
</div>
以下是全部代码
import React, { useEffect, useState } from 'react'
export default function Evaluate() {
// 评论数据
const [list, setList] = useState([
// domeDone 表示
{ name: '匿名用户', rate: 4.5, domeDone: 0 },
{ name: '匿名用户', rate: 5, domeDone: 0 },
{ name: '蛇', rate: 3, domeDone: 0 },
{ name: '匿名用户', rate: 2, domeDone: 3 },
{ name: '匿名用户', rate: 5, domeDone: 0 },
{ name: '匿名用户', rate: 3, domeDone: 0 },
{ name: '熊', rate: 2, domeDone: 3 },
{ name: '匿名用户', rate: 5, domeDone: 2 },
{ name: '长鼻猴', rate: 3, domeDone: 1 },
{ name: '妮数', rate: 2, domeDone: 3 },
])
// 用来控制显示数据
const [type, setType] = useState(undefined)
var sliceList = type === undefined ? list : list.filter(item => item.domeDone === type)
return (
<div id='pinjia'>
<div style={{ padding: '5px' }}>
<span style={type === undefined ? { background: "red" } : {}} onClick={() => { setType(undefined) }}>全部</span>
<span style={type === 1 ? { background: "red" } : {}} onClick={() => { setType(1) }}>最新</span>
<span style={type === 2 ? { background: "red" } : {}} onClick={() => { setType(2) }}>好评</span>
<span style={type === 3 ? { background: "red" } : {}} onClick={() => { setType(3) }}>差评</span>
</div>
<div>
{sliceList.map((item, index) => (
<div className='main-box' key={index}>
<div style={{ float: 'left', width: '30%' }}>
<img src={item.img} />
</div>
<div style={{ float: 'right', width: '70%' }}>
<div>{item.name}</div>
{/* 评分 */}
<Rate readOnly defaultValue={item.rate} allowHalf />
</div>
</div>
))}
</div>
</div>
)
}