我一直在浏览一个 React 文件上传教程,并想添加它。我正在努力做到这一点,因此当用户单击上传消息时,浏览器会提示他们说“您的文件正在上传”我无论如何都不是前端开发人员,所以如果这个问题超级笨,请原谅我。出于某种原因,当我使用此代码时,如果您导航到网页,该函数中的代码将运行一次,然后再次单击。我的预期用途是仅在点击时运行,知道我做错了什么吗?
import React, { Component } from 'react'
import { Alert } from 'react-alert'
class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
imageURL: '',
};
this.handleUploadImage = this.handleUploadImage.bind(this);
}
handleUploadImage(ev) {
ev.preventDefault();
const data = new FormData();
data.append('file', this.uploadInput.files[0]);
data.append('filename', this.fileName.value);
fetch('http://localhost:8000/upload', {
method: 'POST',
body: data,
}).then((response) => {
response.json().then((body) => {
this.setState({ imageURL: `http://localhost:8000/${body.file}` });
});
});
}
render() {
return (
<form onSubmit={this.handleUploadImage}>
<div>
<input ref={(ref) => { this.uploadInput = ref; }} type="file" />
</div>
<div>
<input ref={(ref) => { this.fileName = ref; }} type="text" placeholder="Enter the desired name of file" />
</div>
<br />
<div>
<button onclick="myFunction()">Upload</button>
<script>
function myFunction() {
alert("Your file is being uploaded!")
}
</script>
</div>
<img src={this.state.imageURL} alt="img" />
</form>
);
}
}
export default Main;
原文由 Vincent Morris 发布,翻译遵循 CC BY-SA 4.0 许可协议
为什么不在 handleUploadImage 函数的开头移动警报?
而不是
你将会有