Zha*_* Yi 26 javascript reactjs
我有一个react组件,它呈现一个<input type="file">dom,允许用户从浏览器中选择图像.我发现当我选择相同的文件时,它的onChange方法没有被调用.经过一些搜索,有人建议使用this.value=null或return false在onChange方法的最后,但我尝试它不起作用.
以下是我的代码:
<input id="upload" ref="upload" type="file" accept="image/*"
onChange={(event)=> { this.readFile(event) }}/>
Run Code Online (Sandbox Code Playgroud)
以下是我的尝试:
<input id="upload" ref="upload" type="file" accept="image/*"
onChange={(event)=> {
this.readFile(event)
return false
}}/>
Run Code Online (Sandbox Code Playgroud)
另一个是:
<input id="upload" ref="upload" type="file" accept="image/*"
onChange={(event)=> {
this.readFile(event)
this.value=null
}}/>
Run Code Online (Sandbox Code Playgroud)
我相信上面的解决方案适用于jquery,但我不知道如何让它在reactjs中工作.
jbs*_*ove 51
删除此帖子
<input id="upload" ref="upload" type="file" accept="image/*"
onChange={(event)=> {
this.readFile(event)
}}
onClick={(event)=> {
event.target.value = null
}}
/>
Run Code Online (Sandbox Code Playgroud)
小智 13
经过几个小时的在线研究,这对我在 Reactjs 上有用
<input id="upload" ref="upload" type="file" accept="image/*"
onChange={(event)=> {
//to do
}}
onClick={(e)=> {
e.target.value = null
}}
/>
Run Code Online (Sandbox Code Playgroud)
小智 10
对我来说确实有效:事件。currentTarget .value = null
onClick={(event)=> {
event.currentTarget.value = null
}}
Run Code Online (Sandbox Code Playgroud)
我认为this在你的函数中没有引用input字段.请尝试使用event.target.
<input id="upload" ref="upload" type="file" accept="image/*"
onChange={(event)=> {
this.readFile(event)
event.target.value=null
}}/>
Run Code Online (Sandbox Code Playgroud)
我的反应版本:16.2.0
@jbsmoove解决方案适用于除 IE11 之外的所有浏览器。
对于 IE11,如果我们打开某个文件并在第二次按下打开文件的取消键,它会显示空屏幕,并且在控制台中我们看到:
无法获取未定义或空引用的属性“名称”
所以我想出了另一个即使在 IE11 中也能完美运行的解决方案:
<input id="upload" ref="upload" type="file" accept="image/*"
onInput={(event)=> {
this.readFile(event)
}}
onClick={(event)=> {
event.target.value = null
}}
/>
Run Code Online (Sandbox Code Playgroud)
只需使用onInput而不是onChange。
以下是我的解决方案。(使用打字稿)
import * as React from "react";
export class FileSelector extends React.Component<undefined, undefined>
{
constructor(props: any)
{
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(selectorFiles: FileList)
{
console.log(selectorFiles);
}
render ()
{
return <div>
<input type="file" onChange={ (e) => this.handleChange(e.target.files) } />
</div>;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37747 次 |
| 最近记录: |