【问题标题】:React: input onChange won't fire for the second time, first time it's work反应:输入 onChange 不会触发第二次,第一次工作
【发布时间】:2020-07-28 04:35:35
【问题描述】:

最近我编写了我的 React JS 应用程序来从外部导入图像并处理该图像。为了处理用户onChange事件,我使用onChange来运行我的函数handleChange,但是第二次就不行了。如何正确处理onChange 事件? 这是我的代码

         <div className={classes.fileUpload}>
            <div
              style={{
                position: "relative",
                display: "inline-block",
                height: "100%",
                width: "100%",
              }}
            >
              <input
                type={"file"}
                id="file"
                accept={"image/png, image/jpeg"}
                style={{ display: "none" }}
                onChange={(e) => handleChange(e.target.files)}
              />
              <label htmlFor="file" className={classes.labelFile}>
                <PublishIcon style={{ marginRight: "10px" }} />
                Upload file
              </label>
            </div>
          </div>

【问题讨论】:

  • 第二次选择同一个文件吗?
  • 你试过onInput吗?
  • 谢谢,onInput它的工作

标签: javascript html reactjs


【解决方案1】:

试试这个

import React from 'react'

class SimpleReactFileUpload extends React.Component {

  constructor(props) {
    super(props);
    this.state ={
      file:null
    }
  
    this.onChange = this.onChange.bind(this)
  }

  onChange(e) {
    this.setState({file:e.target.files[0]})
  }


  render() {
    return (
      <form onSubmit={this.onFormSubmit}>
        <h1>File Upload</h1>
        <input type="file" onChange={this.onChange} />
        
      </form>
   )
  }
}



export default SimpleReactFileUpload

希望它会起作用!

【讨论】:

  • 这种复杂的方式来做到这一点。我试过 onInput 和它的工作,谢谢你顺便说一句
猜你喜欢
  • 2020-11-22
  • 2013-11-07
  • 2017-07-19
  • 2023-04-02
  • 2013-08-20
  • 1970-01-01
  • 1970-01-01
  • 2011-11-21
  • 1970-01-01
相关资源
最近更新 更多