繁体   English   中英

有谁知道如何使这个上传的 img function 与旧版本的 reactJS 兼容?

[英]Does anyone know how to make this upload img function compatible with an older version of reactJS?

我不熟悉使用 reactJS(和一般的 JS)。 我正在尝试向现有项目添加一个新的 function 但它不兼容,因为反应依赖项是 16.13.1 并且显然不使用挂钩。 它不接受项目版本中的 useState()。

function App() {
 const [file, setFile] = useState(); // storing the uploaded file
 function handleChange(e) { // function to handle the file upload
 console.log(e.target.files);
 setFile(URL.createObjectURL(e.target.files[0]));
  }

 return (
 <div className="App">
 <h2>Add Image:</h2>
 <input type="file" onChange={handleChange} />
 <img src={file} />

 </div>

  );
}

export default App;

我想让它与那个依赖兼容,但我的尝试还没有成功。 有谁知道如何使其兼容或任何可以提供帮助的资源? 对不起,如果这是一个明显的问题,我还有很多东西要学! 谢谢你!

到目前为止我已经尝试过:

class uploadImage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            subMenuOpen: false,
            file: null 
        }
        this.handleChange = this.handleChange.bind(this)
    }
handleChange = (e) => {
        this.setState({
            file: URL.createObjectURL(e.target.files[0])
        })
    }
render () {
  return (
      <div className="App">
          <h2>Add Image:</h2>
          <input type="file" onChange={handleChange} />
          <img src={file} />

      </div>

  );
}}

也许您应该将 function 转换为Class Component

尝试将<img src={file} />更改为<img src={this.state.file} />

<input type="file" onChange={handleChange} /><input type="file" onChange={this.handleChange} />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM