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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53090699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 10:07:32  来源:igfitidea点击:

How to run an alert on button click React.js

javascriptnode.jsreactjsfrontend

提问by Vincent Morris

I've been running through a react file upload tutorial and want to add on to it. I'm trying to make it so when a user clicks the upload message the browser will prompt them saying "Your file is being uploaded" I'm not a frontend dev by any means so please forgive me if this question is super nooby. For some reason when I use this code, if you navigate to the web page the code in the function runs once, and then again on click. My intended use is to only run on click, any idea what I am doing wrong?

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

采纳答案by Ciprian B

Why don't you move the alert at the begining of handleUploadImage function?

为什么不在 handleUploadImage 函数开始时移动警报?

handleUploadImage(ev) {
    alert("Your file is being uploaded!")
    ....
}

and instead of

而不是

<div>
  <button onclick="myFunction()">Upload</button>
      <script>
      function myFunction() {
          alert("Your file is being uploaded!")
      }
      </script>

</div>

you will have

你将会拥有

<div>
  <button type="submit">Upload</button>
</div>

回答by Vincent Morris

for anyone curious, here is the final code following the help I received.

对于任何好奇的人,这是我收到的帮助后的最终代码。

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) {
    alert("Your file is being uploaded!")
    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 type="submit">Upload</button>
        </div>
        <img src={this.state.imageURL} alt="img" />
      </form>
    );
  }
}

export default Main;

回答by Hemadri Dasari

Change

改变

<form onSubmit={this.handleUploadImage}>

To

<form onSubmit={e => this.handleUploadImage(e)}>

This will call handleUploadImage only when you click

这只会在您单击时调用 handleUploadImage