javascript-如何在按钮上运行警报单击React.js
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript-如何在按钮上运行警报单击React.js,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1717字,纯文字阅读大概需要3分钟。
内容图文
![javascript-如何在按钮上运行警报单击React.js](/upload/InfoBanner/zyjiaocheng/687/c1b28341e6ce4bafb85026afdda37924.jpg)
我一直在浏览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;
解决方法:
为什么不在handleUploadImage函数开始时移动警报?
handleUploadImage(ev) {
alert("Your file is being uploaded!")
....
}
而不是
<div>
<button onclick="myFunction()">Upload</button>
<script>
function myFunction() {
alert("Your file is being uploaded!")
}
</script>
</div>
您将拥有
<div>
<button type="submit">Upload</button>
</div>
内容总结
以上是互联网集市为您收集整理的javascript-如何在按钮上运行警报单击React.js全部内容,希望文章能够帮你解决javascript-如何在按钮上运行警报单击React.js所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。