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

标签 javascript node.js reactjs frontend

我一直在浏览 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/

相关文章:

javascript - jquery show 依次隐藏多个div

javascript - Shiny - 将 javascript 变量存储到 mysql 数据库

node.js - 如何使用 Electron 和 React 显示从文件中读取的数据?

spring-mvc - Spring Boot 与 ReactJS

javascript - 我正在尝试使谷歌图表响应所有设备尺寸

javascript - JQuery 将范围值附加到 textarea 一次

node.js - 尝试使用 SocketIO 和 PHPws 在服务器之间创建套接字

node.js - 在 express.js 上使用(和重用)多个 Mongoose 数据库连接

node.js - 使用 mockery 和 sinon 模拟类方法

reactjs - Mac M1 的 Electron 问题