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

我一直在浏览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 – 在节点js服务器的终端中无法识别nodemon命令


下一篇:PHP-Symfony:如何像在后端一样过滤前端数据