react项目中使用antd及其他注意点小结

antd4.0中使用form组件相关注意点:

1、对多选的下拉框进行改造,加上全选功能

import { Form } from 'antd'
const [form] = Form.useForm()
// 识别类型
    function handleChangeType(value: any) {
        let alg = {}
        let algs = ''
        for (const item of value) {
            // @ts-ignore
            alg = algTypeList.find(i => i.commonName == item)
            // @ts-ignore
            algs += alg.algType + ","
        }
        value.length === algTypeList.length ? setAlgState(true) : setAlgState(false);
        setAlgTypes(algs.substring(0, algs.length - 1))
    }
return(
 <Form style={{ display: 'flex' }} 
       form={form} 
       className="selectGroup1">
   <Form.Item label="识别类型" name="algTypes"
      rules={[{ required: true, message: '请选择或输入识别类型!' }]}
      style={{ marginRight: 15 }}>
      <Select onChange={handleChangeType}
        className="none" mode="multiple" showArrow allowClear
        value={1} maxTagCount={2} style={{ width: 180 }}
        maxTagTextLength={4} placeholder="请选择"
         //@ts-ignore
         defaultValue={defaultType} key={defaultType}
         dropdownRender={allSelectValue => (
        <div>
          <div style={{ padding: '4px 8px 8px 8px', cursor: 'pointer'}}>
           <Checkbox checked={AlgState} onChange={(e) => {
              if (e.target.checked === true) {
                setAlgState(true)
                form.setFieldsValue({
                 algTypes: algTypeList?.map((item: { commonName: any })=> item.commonName)})
             } else {
                setAlgState(false)
                form.setFieldsValue({
                  algTypes: []
                 })
             }
             //调用onchange函数,将下拉框被选中的选项作为value值传入
             handleChangeType(form.getFieldValue('algTypes'))
             }}>全选</Checkbox>
          </div>
          <Divider style={{ margin: '0' }} />
          {allSelectValue}
        </div>)}>
	    {algTypeList.map((item, index) => (
        // @ts-ignore
        <Option value={item.commonName} key={index}>{item.commonName}   </Option>))}
      </Select>
   </Form.Item>
</Form>)

效果:
在这里插入图片描述

2、图片全屏

// 图片全屏
    const setfull = () => {
        const imgFull = document.getElementById('img') as HTMLDivElement
        var RFSN = document.documentElement.requestFullscreen || document.documentElement.requestFullscreen;
        if (RFSN) {
            RFSN.call(imgFull);
        } else if (typeof window.ActiveXObject != "undefined") {
            var wscript = new ActiveXObject("WScript.Shell");
            if (wscript != null) {
                wscript.SendKeys("{F11}");
            }
        }
    }

3、时间选择器

 // 时间切换
const changeDate = (dates: any) => {
	if (dates !== null) {
		setRangeTime({
			startTime: moment(dates[0]).format("YYYY-MM-DD HH:mm:ss"),
			endTime: moment(dates[1]).format("YYYY-MM-DD HH:mm:ss")
		})
	} else {
		setRangeTime({
			startTime: moment().startOf('day').format("YYYY-MM-DD HH:mm:ss"),
			endTime: moment().format("YYYY-MM-DD HH:mm:ss")
		})
	}
}
//默认面板控件显示时间为当天零点到现在的时间
<RangePicker
  	placeholder={['开始时间', '结束时间']}
 	defaultValue={[moment().startOf('day'), moment()]}
  	showTime={{
		hideDisabledOptions: true,
		defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
	}}
	format="YYYY-MM-DD HH:mm:ss"
	onChange={changeDate}
/>

效果:
在这里插入图片描述

4、分页器

 const [pageSize, setPageSize] = useState(10) // 每页记录条数
 // 对总数进行设置时,需指明初始值类型,否则组件中defaultCurrent不生效。
 const [total, setTotal] = useState(1) // 总数
 <Pagination
	style={{ marginTop: 20, textAlign: 'center' }}
	total={total}
	showSizeChanger
	showQuickJumper
	defaultCurrent={1}
	defaultPageSize={pageSize}
	showTotal={total => `共 ${total} 条记录`}
	onChange={changePage}
	pageSizeOptions={[`${pageSize}`]}
/>

效果:
在这里插入图片描述
5、拿到url地址中的相关参数

//上一个页面跳转地址为
history.push(`./project/system/${system.id}?pjId=${pjId}`)
//下一个页面获取相关参数的方法
 const sysId = props.match.params.id
 const pjId = props.location.query.pjId

6、通过url下载图片

export function download(url: string | undefined) {
  const elemIF = document.createElement('iframe');
  elemIF.src = url ? url :'';
  elemIF.style.display = 'none';
  document.body.appendChild(elemIF);
  setTimeout(() => {
    document.body.removeChild(elemIF)
  }, 300)
}

7、通过uuid下载图片

/*
 * 获取下载图片和文件地址
 * th: 原图
 * fileUuid: xxxx-xxxx-xxxx-xxxx-xxxx  || xxx.url
 * */

/*
 * 1: 原图
 * 2: 中大图
 * 3: 中小图
 * 4: 小图
 * */
//fileDownloadUrl.d.ts
export type th = 1 | 2 | 3 | 4;
export type fileDownloadData = {
  th?: th;
  url?: string;
  fileUuid?: string;
};

type FileDownload = (
  th: th,
  fileUuid: string,
  urlPrefix?: string,
) => Promise<string>;

declare const fileDownloadUrl: FileDownload;

export default fileDownloadUrl;

//fileDownloadUrl.ts
import server from '@pms/pmserver';
import request from './utils/request';
const { homeServer } = server;
import { th, fileDownloadData } from './fileDownloadUrl.d';

export default (
  th: th = 4,
  fileUuid: string = '',
  urlPrefix?: string,
): Promise<any> => {
  // 兼容是http的url
  if (fileUuid.includes('http')) return getSourceUrl(fileUuid);
  // 先获取缓存
  const cacheUrl = window.sessionStorage.getItem(fileUuid);
  if (cacheUrl) return getCacheUrl(cacheUrl);
  const data: fileDownloadData = {};
  if (th) data['th'] = th;
  const url = fileUuid.split('-');
  url.length === 5
    ? fileUuid.includes('.')
      ? (data.url = fileUuid)
      : (data.fileUuid = fileUuid)
    : (data.url = fileUuid);
  return new Promise((resolve, reject) => {
    request(`${urlPrefix || homeServer}/common/fileDownloadUrl.htm`, {
      method: 'POST',
      requestType: 'form',
      closeThrowErr: true,
      data,
    })
      .then(res => {
        // 缓存url,减少调用服务端
        if (res) window.sessionStorage.setItem(fileUuid, res);
        resolve(res);
      })
      .catch(err => {
        reject(err);
      });
  });
};

function getSourceUrl(src: string) {
  return new Promise(resolve => {
    resolve(src);
  });
}
function getCacheUrl(src: string) {
  return new Promise(resolve => {
    resolve(src);
  });
}

// 图片下载
import { fileDownloadUrl } from '@pms/react-utils'
    const downloadImg = (uuid: any) => {
        fileDownloadUrl(1, uuid).then(result => {
            window.open(result)
        })
    }

8、通过url导出列表

//例如接口地址为`/eyeai/project/home/deriveFPPLChildPage`,后面拼接的为请求参数
 window.open(`/eyeai/project/home/deriveFPPLChildPage?projectId=${props.pjId || currentUser.pjId}&companyId=${currentUser.coId}&algTypes=${algTypes ? algTypes : ''}&cameraIds=${cameraIds ? cameraIds : ''}&startTime=${rangeTime.startTime}&endTime=${rangeTime.endTime}&selectType=${props.sysId}`, "_blank")

9、为表格设置rowkey

 <Table
	loading={initLoading}
	style={{ maxHeight: 702, overflow: 'auto' }}
	columns={columns}
	dataSource={pageList}
	pagination={false}
	rowKey={record => record.id}
/>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值