Ant|Ant Design的Table组件去除

在Ant Design的Table组件文档中,排序有三种状态:点击升序、点击降序、取消排序。一般需求只需要升序和降序,不需要取消排序,这时候就需要我们设置sortOrder来去除取消排序。
首先,我们从官方文档中ctrl+c出一个排序栗子,放在我们的组件中。
官方栗子

import React, { useEffect, useState } from 'react'; import { Table } from 'antd'export default () => { const [data, setData] = useState([ { key: '1', name: 'John Brown', age: 32, address: 'New York No. 1 Lake Park', }, { key: '2', name: 'Jim Green', age: 42, address: 'London No. 1 Lake Park', }, { key: '3', name: 'Joe Black', age: 30, address: 'Sidney No. 1 Lake Park', }, { key: '4', name: 'Jim Red', age: 25, address: 'London No. 2 Lake Park', }, ] ) const columns: any = [ { title: 'Name', dataIndex: 'name', key: 'name', }, { title: 'Age', dataIndex: 'age', key: 'age', sorter: (a: any, b: any) => a.age - b.age, }, { title: 'Address', dataIndex: 'address', key: 'address', }, ] const onChange = (pagination: any, filters: any, sorter: any, extra: any) => { //pagination分页、filters筛选、sorter排序变化时触发。extra:当前的data console.log(sorter) } return ( ); }
当我们点击排序时,会触发onChange事件,打印出的sorter如下:
Ant|Ant Design的Table组件去除
文章图片

其中,sorter.order为排序状态。undefined:取消排序,ascend:升序,descend:降序。
如何去除取消排序呢?在官方提供的API中,有sortOrder和sortDirections这两个参数,
sortOrder:排序的受控属性,外界可用此控制列的排序,可设置为ascend、descend、false。
sortDirections:支持的排序方式,覆盖Table中sortDirections, 取值为 ascend 、descend。
下面我们就来开始实现去除取消排序。
一、设置sortOrder
首先我们需要声明一个变量sortOrderTest,默认为descend
const [sortOrderTest, setSortOrderTest] = useState('descend')
然后给colum中的排序项Age设置sortOrder
{ title: 'Age', dataIndex: 'age', sortOrder: sortOrderTest, sorter: (a: any, b: any) => a.age - b.age,},

设置完成之后,每次点击排序,发现console输出的一直都是undefined,这是因为我们默认为descend,下一个状态为取消排序,而我们没有去更改sorter状态导致的。所以每次当我们onChange的时候,都要去改变一下设置的变量sortOrderTest
 const onChange = (pagination: any, filters: any, sorter: any, extra: any) => { setSortOrderTest(sorter.order || 'descend') }

只改变sortOrderTest依然是不够的,这时再进行我们的第二步设置。
二、设置sortDirections
{ title: 'Age', dataIndex: 'age', key: 'age', sortOrder: sortOrderTest, sortDirections: ['descend', 'ascend'], sorter: (a: any, b: any) => a.age - b.age, }

【Ant|Ant Design的Table组件去除】这样设置完成之后,Table就去除了取消排序,只剩下升序和降序了。
三、优化
去除取消排序后,表头显示下一次排序的 tooltip 提示一直是点击升序、取消排序循环展示。取消排序其实就是降序,但是不够直观,目前菜菜的我尚未找到如何设置,暂时将tootip关闭。如果你有方法,也可以在评论中告诉我^_^ ,后续我找到方法也会更新哦。要将tootip关闭,showSorterTooltip设置为false即可,具体设置如下:
{ title: 'Age', dataIndex: 'age', key: 'age', sortOrder: sortOrderTest, sortDirections: ['descend', 'ascend'], showSorterTooltip:false, sorter: (a: any, b: any) => a.age - b.age, }

项目中的排序一般是通过接口来排序的,要根据sorter来传不同的参数获取结果,这时候就可以用useEffect来处理。
首先,我们需要将更改column中的sorter,将其置为true。
{ title: 'Age', dataIndex: 'age', key: 'age', sortOrder: sortOrderTest, sortDirections: ['descend', 'ascend'], showSorterTooltip: false, sorter: true, }

然后我们写一个请求函数
const getList = () => { let data = https://www.it610.com/article/{ sort: sortOrderTest } console.log(data) //根据参数去发送请求 //await。。。。 //请求成功之后设置data,达成排序 //setData(result)}

最后,将这个函数放到useEffect中,每当sorter改变的时候,就会自动触发该函数。
useEffect(() => { getList()}, [sortOrderTest])

四、完整代码
import React, { useEffect, useState } from 'react'; import { Table } from 'antd'export default () => { const [sortOrderTest, setSortOrderTest] = useState('descend'); const [data, setData] = useState([ { key: '1', name: 'John Brown', age: 32, address: 'New York No. 1 Lake Park', }, { key: '2', name: 'Jim Green', age: 42, address: 'London No. 1 Lake Park', }, { key: '3', name: 'Joe Black', age: 30, address: 'Sidney No. 1 Lake Park', }, { key: '4', name: 'Jim Red', age: 25, address: 'London No. 2 Lake Park', }, ] ) useEffect(() => { getList() }, [sortOrderTest]) const getList = () => { let data = https://www.it610.com/article/{ sort: sortOrderTest } console.log(data) //根据参数去发送请求 //await。。。。 //请求成功之后设置data,达成排序 //setData(result) } const onChange = (pagination: any, filters: any, sorter: any, extra: any) => { setSortOrderTest(sorter.order || 'descend') } const columns: any = [ { title: 'Name', dataIndex: 'name', key: 'name', }, { title: 'Age', dataIndex: 'age', key: 'age', sortOrder: sortOrderTest, sortDirections: ['descend', 'ascend'], showSorterTooltip: false, sorter: true, }, { title: 'Address', dataIndex: 'address', key: 'address', }, ] return (
); }
补充知识:使用Ant Design的Upload上传删除预览照片,以及上传图片状态一直处于uploading的解决方法。
一、界面构建
1、创建index父组件
import React from "react"; import { Form } from "antd"; import UploadComponent from "./UploadComponent"; export default () => { const [form] = Form.useForm(); return (
); };


2、创建UploadComponent子组件
import React, { useState, useEffect } from "react"; import { Upload } from 'antd'; import { PlusOutlined } from "@ant-design/icons"; export default (props: any) => { console.log(props) const [fileList, setFileList] = useState([]) //展示默认值 const handleChange = ({ file, fileList }: any) => {}; const uploadButton = ( Upload ); return ( {fileList.length >= 8 ? null : uploadButton} ); };


这样一个简单界面就构造完成了,通过打印子组件的props,我们可以看到,父组件给子组件通过prop传递了一个对象,该对象中有value:子组件的默认值,id:FormItem的name,onChange:onChange事件

注:
1、Form表单以及Upload请参考Ant Design官方文档
2、因后台返回数据格式不同,所以fileList的设置也不同,本文仅供参考。
3、本文后台返回的数据格式为:[{id:id1,imgUrl:imgUrl1},...],上传图片成功后,返回的也是一个key值,string类型,比如:qwertyuidsa151sad
二、设置upload的fileList
上传图片后,下次再进入该页面时,Form就会有initialValues默认值,此时upload就要展示默认值中的图片。
fileList是一个数组,数组中是n个对象,每个对象都包含uid:上传图片的id,name:上传图片的名字,status:上传图片的状态,url:图片路径。想展示图片就必须要设置uid,status,url。也可以在该对象中增加自己所需要。
当子组件的props.value变化时,就需要更新fileList,使用useEffect即可。具体代码如下
useEffect(() => { if (props.value) { let newFileList = props.value.map((item: any) => { return {uid: item.id || item.uid,//存在id时,使用默认的id,没有就使用上传图片后自动生成的uidstatus: 'done',//将状态设置为doneurl: 'https://image/'+item.imgUrl,//这里是展示图片的url,根据情况配置imgUrl: item.imgUrl,//添加了一个imgUrl,保存Form时,向后台提交的imgUrl,一个key值 } }) setFileList(newFileList) } }, [props])

三、触发父组件传递的onChange
当子组件每次上传图片或者删除图片时,都需要触发父组件的Onchange事件,来改变Form表单的值。自定义一个triggerChange函数,上传成功或者删除图片时,通过triggerChange来触发onChange。
const triggerChange = (value: any) => { const onChange = props.onChange; if (onChange) { onChange(value); //将改变的值传给父组件 } };

四、file常用的status
1、uploading:上传中
2、done:上传成功
3、error:上传错误
4、removed:删除图片
五、上传图片
上传图片时,触发Upload的onChange事件
const handleChange = ({ file, fileList }: any) => {//file:当前上传的文件//通过map将需要的imgUrl和id添加到file中 fileList = fileList.map((file: any) => { if (file.response) {file.id = file.uid; file.imgUrl = file.response.data.key//请求之后返回的key } return file; }); if (file.status !== undefined) { if (file.status === 'done') { console.log('上传成功') triggerChange(fileList); } else if (file.status === 'error') { console.log('上传失败') } } }


这样之后,会发现上传图片的状态一直是uploading状态,这是因为上传图片的onChange只触发了一次。
解决方法:在onChange中始终setFileList,保证所有状态同步到 Upload 内
const handleChange = ({ file, fileList }: any) => { //...上一段代码//最外层一直设置fileLsit setFileList([...fileList]); }


这样就可以正常上传图片了。
六、删除图片
删除图片时,file的status为removed。具体代码如下
const handleChange = ({ file, fileList }: any) => {//...代码 else if (file.status === 'removed') { if (typeof file.uid === 'number') {//请求接口,删除已经保存过的图片,并且成功之后triggerChangetriggerChange(fileList); } else {//只是上传到了服务器,并没有保存,直接riggerChangetriggerChange(fileList); } }//...代码}

七、预览图片
1、Upload添加onPreview


2、增加Modal
setPreviewVisible(false)}> Ant|Ant Design的Table组件去除


3、添加previewVisible以及previewImage
const [previewVisible, setPreviewVisible] = useState(false);
const [previewImage, setPreviewImage] = useState('');
4、添加handlePreview函数
const handlePreview = async (file: any) => { setPreviewImage(file.imgUrl); //这个图片路径根据自己的情况而定 setPreviewVisible(true); };


这样,图片的上传,删除,预览功能都已经实现了。
八、完整代码
1、index完整代码
index.tsx
import React from "react"; import { Form } from "antd"; import UploadComponent from "./UploadComponent"; export default () => { const [form] = Form.useForm(); return (
); };

2、UploadComponent完整代码
UploadComponent.tsx
import React, { useState, useEffect } from "react"; import { Upload, Modal } from 'antd'; import { PlusOutlined } from "@ant-design/icons"; export default (props: any) => { console.log(props) const [fileList, setFileList] = useState([]) const [previewVisible, setPreviewVisible] = useState(false); const [previewImage, setPreviewImage] = useState(''); useEffect(() => { if (props.value) { let newFileList = props.value.map((item: any) => { return {uid: item.id || item.uid,status: 'done',url: 'url' + item.imgUrl,imgUrl: item.imgUrl, } }) setFileList(newFileList) } }, [props]) const handleChange = ({ file, fileList }: any) => { fileList = fileList.map((file: any) => { if (file.response) { file.id = file.uid; file.imgUrl = file.response.data.key } return file; }); if (file.status !== undefined) { if (file.status === 'done') { console.log('上传成功') triggerChange(fileList); } else if (file.status === 'error') { console.log('上传失败') } else if (file.status === 'removed') { if (typeof file.uid === 'number') {//请求接口,删除已经保存过的图片,并且成功之后triggerChangetriggerChange(fileList); } else {//只是上传到了服务器,并没有保存,直接riggerChangetriggerChange(fileList); } } } setFileList([...fileList]); } const triggerChange = (value: any) => { const onChange = props.onChange; if (onChange) { onChange(value); } }; const handlePreview = async (file: any) => { setPreviewImage(`url/${file.imgUrl}`); setPreviewVisible(true); }; const uploadButton = ( Upload ); return ( {fileList.length >= 8 ? null : uploadButton} setPreviewVisible(false)} > Ant|Ant Design的Table组件去除 ); };

以上这篇Ant Design的Table组件去除“取消排序”选项操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

    推荐阅读