溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何使用Ant Design的Table組件取消排序

發(fā)布時(shí)間:2020-10-26 14:00:30 來源:億速云 閱讀:1172 作者:Leah 欄目:開發(fā)技術(shù)

今天就跟大家聊聊有關(guān)如何使用Ant Design的Table組件取消排序,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

在Ant Design的Table組件文檔中,排序有三種狀態(tài):點(diǎn)擊升序、點(diǎn)擊降序、取消排序。一般需求只需要升序和降序,不需要取消排序,這時(shí)候就需要我們設(shè)置sortOrder來去除取消排序。

首先,我們從官方文檔中ctrl+c出一個(gè)排序栗子,放在我們的組件中。

官方栗子

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排序變化時(shí)觸發(fā)。extra:當(dāng)前的data
 console.log(sorter)
 }
 return (
 <div>
 <Table columns={columns} dataSource={data} onChange={onChange} />
 </div>
 );
}

當(dāng)我們點(diǎn)擊排序時(shí),會觸發(fā)onChange事件,打印出的sorter如下:

如何使用Ant Design的Table組件取消排序

其中,sorter.order為排序狀態(tài)。undefined:取消排序,ascend:升序,descend:降序。

如何去除取消排序呢?在官方提供的API中,有sortOrder和sortDirections這兩個(gè)參數(shù),

sortOrder:排序的受控屬性,外界可用此控制列的排序,可設(shè)置為ascend、descend、false?!    ?/p>

sortDirections:支持的排序方式,覆蓋Table中sortDirections, 取值為 ascend 、descend。

下面我們就來開始實(shí)現(xiàn)去除取消排序。

一、設(shè)置sortOrder

首先我們需要聲明一個(gè)變量sortOrderTest,默認(rèn)為descend

const [sortOrderTest, setSortOrderTest] = useState<string>('descend')

然后給colum中的排序項(xiàng)Age設(shè)置sortOrder

{
 title: 'Age',
 dataIndex: 'age',
 sortOrder: sortOrderTest,
 sorter: (a: any, b: any) => a.age - b.age,
},

設(shè)置完成之后,每次點(diǎn)擊排序,發(fā)現(xiàn)console輸出的一直都是undefined,這是因?yàn)槲覀兡J(rèn)為descend,下一個(gè)狀態(tài)為取消排序,而我們沒有去更改sorter狀態(tài)導(dǎo)致的。所以每次當(dāng)我們onChange的時(shí)候,都要去改變一下設(shè)置的變量sortOrderTest

 const onChange = (pagination: any, filters: any, sorter: any, extra: any) => {
 setSortOrderTest(sorter.order || 'descend')
 }

只改變sortOrderTest依然是不夠的,這時(shí)再進(jìn)行我們的第二步設(shè)置。

二、設(shè)置sortDirections

 {
 title: 'Age',
 dataIndex: 'age',
 key: 'age',
 sortOrder: sortOrderTest,
 sortDirections: ['descend', 'ascend'],
 sorter: (a: any, b: any) => a.age - b.age,
 }

這樣設(shè)置完成之后,Table就去除了取消排序,只剩下升序和降序了。

三、優(yōu)化

去除取消排序后,表頭顯示下一次排序的 tooltip 提示一直是點(diǎn)擊升序、取消排序循環(huán)展示。取消排序其實(shí)就是降序,但是不夠直觀,目前菜菜的我尚未找到如何設(shè)置,暫時(shí)將tootip關(guān)閉。如果你有方法,也可以在評論中告訴我^_^ ,后續(xù)我找到方法也會更新哦。要將tootip關(guān)閉,showSorterTooltip設(shè)置為false即可,具體設(shè)置如下:

{
 title: 'Age',
 dataIndex: 'age',
 key: 'age',
 sortOrder: sortOrderTest,
 sortDirections: ['descend', 'ascend'],
 showSorterTooltip:false,
 sorter: (a: any, b: any) => a.age - b.age,
 }

項(xiàng)目中的排序一般是通過接口來排序的,要根據(jù)sorter來傳不同的參數(shù)獲取結(jié)果,這時(shí)候就可以用useEffect來處理。

首先,我們需要將更改column中的sorter,將其置為true。

{
 title: 'Age',
 dataIndex: 'age',
 key: 'age',
 sortOrder: sortOrderTest,
 sortDirections: ['descend', 'ascend'],
 showSorterTooltip: false,
 sorter: true,
 }

然后我們寫一個(gè)請求函數(shù)

const getList = () => {
 let data = {
 sort: sortOrderTest
 }
 console.log(data)
 //根據(jù)參數(shù)去發(fā)送請求
 //await。。。。
 //請求成功之后設(shè)置data,達(dá)成排序
 //setData(result)
}

最后,將這個(gè)函數(shù)放到useEffect中,每當(dāng)sorter改變的時(shí)候,就會自動觸發(fā)該函數(shù)。

useEffect(() => {
 getList()
}, [sortOrderTest])

四、完整代碼

import React, { useEffect, useState } from 'react';
import { Table } from 'antd'

export default () => {
 const [sortOrderTest, setSortOrderTest] = useState<string>('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 = {
 sort: sortOrderTest
 }
 console.log(data)
 //根據(jù)參數(shù)去發(fā)送請求
 //await。。。。
 //請求成功之后設(shè)置data,達(dá)成排序
 //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 (
 <div>
 <Table columns={columns} dataSource={data} onChange={onChange} />
 </div>
 );
}

補(bǔ)充知識:使用Ant Design的Upload上傳刪除預(yù)覽照片,以及上傳圖片狀態(tài)一直處于uploading的解決方法。

一、界面構(gòu)建  

1、創(chuàng)建index父組件

import React from "react";
import { Form } from "antd";
import UploadComponent from "./UploadComponent";
export default () => {
 const [form] = Form.useForm();
 return (
 <Form
 form={form}
 initialValues={
 {
  'uploadPhoto': []
 }
 }
 >
 <Form.Item name="uploadPhoto">
 <UploadComponent />
 </Form.Item>
 </Form>
 );
};

2、創(chuàng)建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<any>([]) //展示默認(rèn)值
 const handleChange = ({ file, fileList }: any) => {};
 const uploadButton = (
 <div>
 <PlusOutlined />
 <div className="ant-upload-text">Upload</div>
 </div>
 );
 return (
 <Upload
 listType="picture-card"
 fileList={fileList}
 onChange={handleChange}
 action={'這里是你上傳圖片的地址'}
 >
 {fileList.length >= 8 &#63; null : uploadButton}
 </Upload>
 );
};

這樣一個(gè)簡單界面就構(gòu)造完成了,通過打印子組件的props,我們可以看到,父組件給子組件通過prop傳遞了一個(gè)對象,該對象中有value:子組件的默認(rèn)值,id:FormItem的name,onChange:onChange事件

注:

1、Form表單以及Upload請參考Ant Design官方文檔  

2、因后臺返回?cái)?shù)據(jù)格式不同,所以fileList的設(shè)置也不同,本文僅供參考?! ?/p>

3、本文后臺返回的數(shù)據(jù)格式為:[{id:id1,imgUrl:imgUrl1},...],上傳圖片成功后,返回的也是一個(gè)key值,string類型,比如:qwertyuidsa151sad

二、設(shè)置upload的fileList   

上傳圖片后,下次再進(jìn)入該頁面時(shí),F(xiàn)orm就會有initialValues默認(rèn)值,此時(shí)upload就要展示默認(rèn)值中的圖片。

   fileList是一個(gè)數(shù)組,數(shù)組中是n個(gè)對象,每個(gè)對象都包含uid:上傳圖片的id,name:上傳圖片的名字,status:上傳圖片的狀態(tài),url:圖片路徑。想展示圖片就必須要設(shè)置uid,status,url。也可以在該對象中增加自己所需要。  

當(dāng)子組件的props.value變化時(shí),就需要更新fileList,使用useEffect即可。具體代碼如下

useEffect(() => {
 if (props.value) {
 let newFileList = props.value.map((item: any) => {
 return {
  uid: item.id || item.uid,      //存在id時(shí),使用默認(rèn)的id,沒有就使用上傳圖片后自動生成的uid
  status: 'done',            //將狀態(tài)設(shè)置為done  
  url: 'https://image/'+item.imgUrl,  //這里是展示圖片的url,根據(jù)情況配置
  imgUrl: item.imgUrl,  //添加了一個(gè)imgUrl,保存Form時(shí),向后臺提交的imgUrl,一個(gè)key值
 }
 })
 setFileList(newFileList)
 }
 }, [props])

三、觸發(fā)父組件傳遞的onChange   

當(dāng)子組件每次上傳圖片或者刪除圖片時(shí),都需要觸發(fā)父組件的Onchange事件,來改變Form表單的值。自定義一個(gè)triggerChange函數(shù),上傳成功或者刪除圖片時(shí),通過triggerChange來觸發(fā)onChange。

 const triggerChange = (value: any) => {
 const onChange = props.onChange;  
 if (onChange) {
 onChange(value); //將改變的值傳給父組件
 }
 };

四、file常用的status   

1、uploading:上傳中

   2、done:上傳成功

   3、error:上傳錯(cuò)誤

   4、removed:刪除圖片

五、上傳圖片  

上傳圖片時(shí),觸發(fā)Upload的onChange事件

 const handleChange = ({ file, fileList }: any) => {
  //file:當(dāng)前上傳的文件
  //通過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('上傳失敗')
 }
 }
 }

這樣之后,會發(fā)現(xiàn)上傳圖片的狀態(tài)一直是uploading狀態(tài),這是因?yàn)樯蟼鲌D片的onChange只觸發(fā)了一次。

  解決方法:在onChange中始終setFileList,保證所有狀態(tài)同步到 Upload 內(nèi)

 const handleChange = ({ file, fileList }: any) => {
 //...上一段代碼
   //最外層一直設(shè)置fileLsit
 setFileList([...fileList]);
 }

這樣就可以正常上傳圖片了。

六、刪除圖片  

刪除圖片時(shí),file的status為removed。具體代碼如下

 const handleChange = ({ file, fileList }: any) => {
   //...代碼 
   else if (file.status === 'removed') {
 if (typeof file.uid === 'number') {
  //請求接口,刪除已經(jīng)保存過的圖片,并且成功之后triggerChange
  triggerChange(fileList);
 } else {
  //只是上傳到了服務(wù)器,并沒有保存,直接riggerChange
  triggerChange(fileList);
 }
 }
  //...代碼
}

七、預(yù)覽圖片  

1、Upload添加onPreview

<Upload
 onPreview={handlePreview}
 >
</Upload>

2、增加Modal

<Modal
 visible={previewVisible}
 title='預(yù)覽照片'
 footer={null}
 onCancel={() => setPreviewVisible(false)}
>
 <img alt="example" style={{ width: '100%' }} src={previewImage} />
</Modal>

3、添加previewVisible以及previewImage

const [previewVisible, setPreviewVisible] = useState<boolean>(false);

const [previewImage, setPreviewImage] = useState<string>('');   

4、添加handlePreview函數(shù)

 const handlePreview = async (file: any) => {
 setPreviewImage(file.imgUrl); //這個(gè)圖片路徑根據(jù)自己的情況而定
 setPreviewVisible(true);
 };

這樣,圖片的上傳,刪除,預(yù)覽功能都已經(jīng)實(shí)現(xiàn)了。

八、完整代碼  

1、index完整代碼

index.tsx

import React from "react";
import { Form } from "antd";
import UploadComponent from "./UploadComponent";
export default () => {
 const [form] = Form.useForm();
 return (
 <Form
 form={form}
 initialValues={
 {
  'uploadPhoto': []
 }
 }
 >
 <Form.Item name="uploadPhoto">
 <UploadComponent />
 </Form.Item>
 </Form>
 );
};

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<any>([])
 const [previewVisible, setPreviewVisible] = useState<boolean>(false);
 const [previewImage, setPreviewImage] = useState<string>('');
 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') {
  //請求接口,刪除已經(jīng)保存過的圖片,并且成功之后triggerChange
  triggerChange(fileList);
 } else {
  //只是上傳到了服務(wù)器,并沒有保存,直接riggerChange
  triggerChange(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 = (
 <div>
 <PlusOutlined />
 <div className="ant-upload-text">Upload</div>
 </div>
 );
 return (
 <div>
 <Upload
 listType="picture-card"
 fileList={fileList}
 onChange={handleChange}
 onPreview={handlePreview}
 action={'url'}
 headers={{
  'Duliday-Agent': '4',
  'Duliday-Agent-Version': (0x020000).toString(),
  'X-Requested-With': 'null',
  'token': 'token'
 }}
 >
 {fileList.length >= 8 &#63; null : uploadButton}
 </Upload>
 <Modal
 visible={previewVisible}
 title='預(yù)覽照片'
 footer={null}
 onCancel={() => setPreviewVisible(false)}
 >
 <img alt="example" style={{ width: '100%' }} src={previewImage} />
 </Modal>
 </div>
 );
};

看完上述內(nèi)容,你們對如何使用Ant Design的Table組件取消排序有進(jìn)一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI