小编S_F*_*sai的帖子

输入的event.target在this.setState中为null [React.js]

在我的react组件中,我有一个文件输入:

<input type="file" onChange={this.onFileChange.bind(this)} />` 
Run Code Online (Sandbox Code Playgroud)

而我的onFileChange是:

onFileChange(e) {
  let file = e.target.files[0];
  this.setState(() => ({ file: e.target.files[0] })); //doesnt work
  // this.setState(() => ({ file })); //works
  // this.setState({ file: e.target.files[0] }); //works
}
Run Code Online (Sandbox Code Playgroud)

设置状态的第一种方法失败并出现错误:

Cannot read property 'files' of null
Run Code Online (Sandbox Code Playgroud)

React还提供以下警告:

This synthetic event is reused for performance reasons. If you're 
seeing this, you're accessing the property 'target' on a 
released/nullified synthetic event
Run Code Online (Sandbox Code Playgroud)

但是设置状态的最后两种方式不会给出任何错误或警告.为什么会这样?

html javascript reactjs

13
推荐指数
1
解决办法
1万
查看次数

标签 统计

html ×1

javascript ×1

reactjs ×1