【发布时间】:2019-04-05 01:16:13
【问题描述】:
我一直在运行一个反应文件上传教程,并想添加到它。我正在努力做到这一点,因此当用户单击上传消息时,浏览器会提示他们说“您的文件正在上传”,无论如何我都不是前端开发人员,所以如果这个问题是超级笨蛋,请原谅我。出于某种原因,当我使用此代码时,如果您导航到网页,函数中的代码会运行一次,然后在单击时再次运行。我的预期用途是仅在点击时运行,知道我做错了什么吗?
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;
【问题讨论】:
-
尝试将
<button onclick="myFunction()">更改为<button onClick={myFunction}>。 -
@byrdEmmanuel 当我尝试时,我收到一条新的错误消息:第 48 行:'myFunction' is not defined no-undef
-
也尝试按照您在上面发布的方式将函数括在引号中不会引发错误,但会在页面加载/刷新时提醒浏览器
-
将
myFunction定义在与handleUpdateImage相同的级别而不是<script>标记中,它应该像那样工作。
标签: javascript node.js reactjs frontend