react antd專案開發過程元件使用問題(不定期更新)
阿新 • • 發佈:2021-01-17
技術標籤:antd元件的使用問題reactjavascript
一、Form元件自定義驗證設定問題**
<Form.Item
key={index}
label={item.name}
name={item.field}
rules={[
{
required: item.required,
message: item.name+'不能為空',
},
({ getFieldValue }) => ({
validator(_, value) {此處自己根據需求新增驗證判斷方法
if(!value && item.required) {///
return Promise.reject(item.name+'不能為空');
}
if (value && item.field==='phone') {
let reg = /^[1][3,4,5,7,8,9][0-9]{9}$/;///手機號正則驗證
if (!reg.test(value)){
return Promise.reject('手機號輸入不正確');
}
}
return Promise.resolve();
},
}),
]}
required={item.required}
>
<Input onChange={(event)=>onValueChange(event,item.field)} />
</Form.Item>
return Promise.resolve();
這一行不能省略,不然會導致onFinish方法不生效,獲取不到Form表單填寫的資訊
** 二、圖片上傳自定義上傳方法**
上傳元件添里加自定義方法欄位customRequest
,覆蓋預設的上傳方法,其使用方式參考onChange
事件
customRequest= options =>{
const { onSuccess, onError, file, onProgress } = options;
console.log(file);
const formData = new FormData();
formData.append("name", file.name);
const reader = new FileReader();
reader.readAsDataURL(file); // 讀取圖片檔案
reader.onload = (e) => {
console.log(e);
let url=e.target.result;//獲取圖片base64編碼
formData.append("file", file, url);
// 上傳圖片的base64編碼
axios.post('/api/common_file/',formData)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error.response);
});
};
};
三、仿造antd的input圖片上傳,寫個自己的元件
建立uploadImg.js和uploadImg.css檔案
//uploadImg.js
import React from "react";
import axios from "../request/axios";
import {message} from "antd";
import './uploadImg.css'
/* 圖片上傳事件 */
function OnUploadImg(id,url,callback) {
if(document.getElementById(id).files.length>0){///判斷一下是否選擇了圖片,不然點選取消按鈕會報錯
let imgfile=document.getElementById(id).files[0];//獲取圖片物件資訊
let imgUrl=document.getElementById(id).value; //獲取圖片連結地址
const isLt2M = imgfile.size / 1024 / 1024 < 2; //計算圖片的大小是否小於2M
if(imgfile.type==='image/jpeg' || imgfile.type==='image/png'){//判斷是否選擇的是圖片
if(!isLt2M){
message.error(' 圖片大小不能超過 2MB!');
}else {
let formdata = new FormData();
formdata.append("name", imgfile.name);
formdata.append("file", imgfile, imgUrl);
axios.post(url,formdata)
.then(function (response) {
callback.call(this,response);
message.error('圖片上傳成功')
})
.catch(function (error) {
message.error('圖片上傳失敗,請重新上傳!')
});
}
}else {
message.error('圖片上傳格式應為png/jpg!')
}
}
}
function onClearImg(id,onClear){//清除選擇的圖片檔案
let file=document.getElementById(id);
file.value=null;
onClear()
}
/*
* id為檔案的id
* title設定加號下面顯示的文字內容
* imgUrl是預設的圖片地址
* onChange是選擇檔案事件
* onClear圖片清除事件
* */
function UploadImg(props) {
let {id,title,imgUrl,onChange,onClear}=props;
return (
<div className='updateImg ant-upload ant-upload-select ant-upload-select-picture-card'>
<input type='file' id={id} onChange={()=>onChange(id)} accept="image/jpg,image/png,image/jpeg," />
<div className='file_add'>
<p>+</p>
<p>{title?title:'上傳圖片'}</p>
</div>
{imgUrl?<img alt='' src={imgUrl} />:""}
{
imgUrl? <div className='clearImg' onClick={()=>onClearImg(id,onClear)}>+</div>:''
}
</div>
)
}
/* 元件和onChange上傳事件 */
export {UploadImg,OnUploadImg}
.updateImg {
position: relative;
}
.updateImg input {
width: 100%;
height: 100%;
overflow: hidden;
position: relative;
z-index: 2;
outline: none;
opacity: 0;
}
.updateImg .file_add{
width: 100%;
height: 100%;
position: absolute;
left: 0;
top: 0;
color: #999999;
}
.updateImg .file_add p:first-child{
width: 100%;
height: 50%;
padding-top: 5px;
font-size: 35px;
text-align: center;
}
.updateImg img{
width: 100%;
height: 100%;
position: absolute;
left: 0;
top: 0;
z-index: 3;
}
.updateImg .clearImg{
transform: rotate(45deg);
width: 18px;
height: 18px;
background-color: #9a9a9a;
color: #ffffff;
text-align: center;
line-height: 16px;
position: absolute;
right: 4px;
top: 4px;
z-index: 5;
border-radius: 50%;
font-size: 18px;
user-select:none;
}
引用元件
import {UploadImg,OnUploadImg} from '../../components/uploadImg/uploadImg'
OnUploadImg1=(id,url)=>{
let _this=this;
OnUploadImg(id,url,function (response) {//response為介面返回的資料
console.log(response);//此處進行一些操作,比如說將返回的地址顯示在頁面上
_this.setState({
img1:response.file
})
})
};
ClearImg(){//清除圖片
this.setState({
img1:''
})
}
<UploadImg
id='img1'
imgUrl={this.state.img1}
title='上傳頭像'//自定義文字
onChange={()=>this.OnUploadImg1('img1','/api/common_file/')}
onClear={this.ClearImg.bind(this)}
/>
效果如下圖