[英]Does anyone know how to make this upload img function compatible with an older version of reactJS?
I am new to using reactJS (and JS in general).我不熟悉使用 reactJS(和一般的 JS)。 I am trying to add a new function to an existing project but it is not compatible because the react dependency is 16.13.1 and does not use hooks apparently.我正在尝试向现有项目添加一个新的 function 但它不兼容,因为反应依赖项是 16.13.1 并且显然不使用挂钩。 It doesn't accept useState() in the version of the project.它不接受项目版本中的 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;
I want to make this compatible with that dependency but I have had no luck with my attempts yet.我想让它与那个依赖兼容,但我的尝试还没有成功。 does anyone know how to make it compatible or any resources that can help?有谁知道如何使其兼容或任何可以提供帮助的资源? sorry if this is an obvious question, I still have a lot to learn!对不起,如果这是一个明显的问题,我还有很多东西要学! thank you!谢谢你!
What I've tried so far:到目前为止我已经尝试过:
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>
);
}}
maybe you should convert your function into Class Component
也许您应该将 function 转换为Class Component
try change <img src={file} />
to <img src={this.state.file} />
尝试将<img src={file} />
更改为<img src={this.state.file} />
<input type="file" onChange={handleChange} />
to <input type="file" onChange={this.handleChange} />
<input type="file" onChange={handleChange} />
到<input type="file" onChange={this.handleChange} />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.