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 ( <div> <Table columns={columns} dataSource={data} onChange={onChange} /> </div> ); }
當我們點選排序時,會觸發onChange事件,打印出的sorter如下:
其中,sorter.order為排序狀態。undefined:取消排序,ascend:升序,descend:降序。
如何去除取消排序呢?在官方提供的API中,有sortOrder和sortDirections這兩個引數,
sortOrder:排序的受控屬性,外界可用此控制列的排序,可設定為ascend、descend、false。
sortDirections:支援的排序方式,覆蓋Table中sortDirections, 取值為 ascend 、descend。
下面我們就來開始實現去除取消排序。
一、設定sortOrder
首先我們需要宣告一個變數sortOrderTest,預設為descend
const [sortOrderTest,setSortOrderTest] = useState<string>('descend')
然後給colum中的排序項Age設定sortOrder
{ title: 'Age',sortOrder: sortOrderTest,
設定完成之後,每次點選排序,發現console輸出的一直都是undefined,這是因為我們預設為descend,下一個狀態為取消排序,而我們沒有去更改sorter狀態導致的。所以每次當我們onChange的時候,都要去改變一下設定的變數sortOrderTest
const onChange = (pagination: any,extra: any) => { setSortOrderTest(sorter.order || 'descend') }
只改變sortOrderTest依然是不夠的,這時再進行我們的第二步設定。
二、設定sortDirections
{ title: 'Age',sortDirections: ['descend','ascend'],}
這樣設定完成之後,Table就去除了取消排序,只剩下升序和降序了。
三、優化
去除取消排序後,表頭顯示下一次排序的 tooltip 提示一直是點選升序、取消排序迴圈展示。取消排序其實就是降序,但是不夠直觀,目前菜菜的我尚未找到如何設定,暫時將tootip關閉。如果你有方法,也可以在評論中告訴我^_^ ,後續我找到方法也會更新哦。要將tootip關閉,showSorterTooltip設定為false即可,具體設定如下:
{ title: 'Age',showSorterTooltip:false,}
專案中的排序一般是通過介面來排序的,要根據sorter來傳不同的引數獲取結果,這時候就可以用useEffect來處理。
首先,我們需要將更改column中的sorter,將其置為true。
{ title: 'Age',showSorterTooltip: false,sorter: true,}
然後我們寫一個請求函式
const getList = () => { let data = { sort: sortOrderTest } console.log(data) //根據引數去傳送請求 //await。。。。 //請求成功之後設定data,達成排序 //setData(result) }
最後,將這個函式放到useEffect中,每當sorter改變的時候,就會自動觸發該函式。
useEffect(() => { getList() },[sortOrderTest])
四、完整程式碼
import React,useState } from 'react'; import { Table } from 'antd' export default () => { const [sortOrderTest,setSortOrderTest] = useState<string>('descend'); const [data,] ) useEffect(() => { getList() },[sortOrderTest]) const getList = () => { let data = { sort: sortOrderTest } console.log(data) //根據引數去傳送請求 //await。。。。 //請求成功之後設定data,達成排序 //setData(result) } const onChange = (pagination: any,extra: any) => { setSortOrderTest(sorter.order || 'descend') } const columns: any = [ { title: 'Name',] return ( <div> <Table columns={columns} dataSource={data} onChange={onChange} /> </div> ); }
補充知識:使用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 ( <Form form={form} initialValues={ { 'uploadPhoto': [] } } > <Form.Item name="uploadPhoto"> <UploadComponent /> </Form.Item> </Form> ); };
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<any>([]) //展示預設值 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 ? null : uploadButton} </Upload> ); };
這樣一個簡單介面就構造完成了,通過列印子元件的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,沒有就使用上傳圖片後自動生成的uid status: 'done', //將狀態設定為done url: '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') { //請求介面,刪除已經儲存過的圖片,並且成功之後triggerChange triggerChange(fileList); } else { //只是上傳到了伺服器,並沒有儲存,直接riggerChange triggerChange(fileList); } } //...程式碼 }
七、預覽圖片
1、Upload新增onPreview
<Upload onPreview={handlePreview} > </Upload>
2、增加Modal
<Modal visible={previewVisible} title='預覽照片' 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函式
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 ( <Form form={form} initialValues={ { 'uploadPhoto': [] } } > <Form.Item name="uploadPhoto"> <UploadComponent /> </Form.Item> </Form> ); };
2、UploadComponent完整程式碼
UploadComponent.tsx
import React,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') { //請求介面,刪除已經儲存過的圖片,並且成功之後triggerChange triggerChange(fileList); } else { //只是上傳到了伺服器,並沒有儲存,直接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 ? null : uploadButton} </Upload> <Modal visible={previewVisible} title='預覽照片' footer={null} onCancel={() => setPreviewVisible(false)} > <img alt="example" style={{ width: '100%' }} src={previewImage} /> </Modal> </div> ); };
以上這篇Ant Design的Table元件去除“取消排序”選項操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。