c#做asp.net網(wǎng)站余姚網(wǎng)站seo運(yùn)營
最近的需求,兩個下拉框是必填項(xiàng),點(diǎn)擊上傳按鈕,如果有下拉框沒選要有提示,如圖
如果直接使用antd的Upload組件,一點(diǎn)擊文件選擇的窗口就打開了,哪怕在Button里再加點(diǎn)擊事件,也只是(幾乎)同時處理兩個方法,beforeUpload更是不行,文件都選擇完了才執(zhí)行。
在網(wǎng)上查找,終于看到這位vue選手的一個思路,兩個同位置同樣式的按鈕按某個state切換:
AntD框架上傳文件前校驗(yàn)信息:選擇文件前進(jìn)行內(nèi)容校驗(yàn)并提示
改成react寫法,把除了文件以外的payload獲取放到beforeUpload里
const [uploadData, setUpLoadData] = useState(null);
const [selectMonth, setSelectMonth] = useState(false);
const [selectaaa, setSelectaaa] = useState(false);const handleBeforeUpload = file => {if (!/.xls?$/.test(file.name) && !/.xlsx?$/.test(file.name)) {message.error('...');return false;}form.validateFields((err, fieldsValue) => {if (err) return;const month = moment(fieldsValue.month).format('YYYY-MM');setUpLoadData({...fieldsValue, month: month});});return true;
};
組件里加onChange監(jiān)聽:
<FormItem label="月份" {...formItemLayout}> {getFieldDecorator('month', {rules: [{ required: true, message: '請選擇月份' }],})(<MonthPicker onChange={value => value ? setSelectMonth(true) : setSelectMonth(false)}/>)}
</FormItem>
最后上傳按鈕那邊做兩個按鈕,用最上面定義的兩個state來確定展示哪個按鈕(validate里調(diào)用form.validateFields方法做必填提示):
{selectDepartment && selectMonth ? (<Uploadaction={uploadUrl}data={uploadData}showUploadList={false}onChange={handleUpload}beforeUpload={handleBeforeUpload}withCredentialsheaders={}><Button type="primary" style={}><Icon type='cloud-upload' /> 上傳數(shù)據(jù) </Button></Upload>
) : (<Button type="primary" style={} onClick={()=>validate()}><Icon type='cloud-upload' /> 上傳數(shù)據(jù) </Button> )
}
就可以做到最開始提到的效果啦。
又看到一篇文章(https://zhuanlan.zhihu.com/p/590018131?utm_id=0),可以更優(yōu)雅地監(jiān)聽form,不用再使用onChange方法和useState,改完發(fā)現(xiàn)自己項(xiàng)目antd版本太低了用不了,從antd@4.20.0
?開始,antd
?Form 添加了一個新的 API ->Form.useWatch
const [form] = Form.useForm();
const aaa = Form.useWatch('aaa', form);
const month = Form.useWatch('month', form);
在form item標(biāo)簽里加上name屬性:
<FormItem label="月份" {...formItemLayout} name='month'>
效果應(yīng)該是一樣的。
另外發(fā)現(xiàn)使用dataform格式post方法上傳文件,其他數(shù)據(jù)參數(shù)不需要用new FormData()再append進(jìn)去了,直接傳字典就行。