gpt4 book ai didi

javascript - 如何在按钮单击 React.js 时运行警报

转载 作者:搜寻专家 更新时间:2023-10-31 23:03:03 25 4
gpt4 key购买 nike

我一直在浏览 React 文件上传教程,并想对其进行补充。我正在努力做到这一点,因此当用户单击上传消息时,浏览器会提示他们说“您的文件正在上传”我无论如何都不是前端开发人员,所以如果这个问题 super 笨,请原谅我。出于某种原因,当我使用此代码时,如果您导航到网页,该函数中的代码将运行一次,然后再次单击。我的预期用途是仅在点击时运行,知道我做错了什么吗?

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;

最佳答案

为什么不把 alert 移到 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 时运行警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53090699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com