表单重置type=“file“的input、form.reset用法

36 篇文章 0 订阅
14 篇文章 0 订阅

一、场景

  1. 利用原始html input-type=“file” 写了一个上传文件的组件、但是每次上传之后,
  2. 再次选择文件就不会触发 onchange 事件, 上传导致页面报错
// trigger select file
getFilds = () =>{
  const filedom = document.getElementById('file');
  filedom.click()
}
// This function is used to listen for events uploaded by the button
fileinputChange = (event) =>{
  const fileData = event.target.files[0];
  if(fileData) this.send(fileData);
}

send = (fileData) =>{
	fetch(...).then(res=>{
		// promit infomation to users
		... 
	})
}
... render
<div>
	<input 
	  type="file" id="file" accept=".xls,.xlsx"
	  style={{ display:"none", }} onChange={this.fileinputChange}
	/>
	<Button type="primary" onClick={this.getFilds}>上传excel</Button>
</div>

二、解决办法

使用 html-form-reset() 方法重置 type=“file” 的值。
form-reset MDN 使用方法传送门 https://developer.mozilla.org/
修改html code如下

// trigger select file
getFilds = () =>{...}
// This function is used to listen for events uploaded by the button
fileinputChange = (event) =>{...}

send = (fileData) =>{
	fetch(...).then(res=>{
		// promit infomation to users
		... 
		// 在这里加入表单重置
		const filedom = document.getElementById('Formreset');
		filedom.reset()
	})
}



<form id="Formreset">
	<input 
	  type="file" id="file" accept=".xls,.xlsx"
	  style={{ display:"none", }} onChange={this.fileinputChange}
	/>
	<Button type="primary" onClick={this.getFilds}>上传excel</Button>
</form>

三、注意事项

form.reset() 方法会表单项表单内所有表单项
运行该方法和点击表单的重置按钮是一样的效果.

因为案例这里我只有一个input表单项用于获取文件,所以使用这个方法最合适。
内容如果对你有帮助,点个赞吧 ~~

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值