首页 > 解决方案 > 不确定如何将此类组件编写为钩子

问题描述

我尝试将以下代码编写为钩子,但它返回错误。uploadinput 和 filename 变量在这里没有初始化。当我尝试将下面的代码转换为钩子时,它说找不到这两个变量。

import React from 'react'

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>
            <text>{"\n\n"}</text>
              <input ref={(ref) => { this.uploadInput = ref; }} type="file" />
            </div>
            <text>{"\n\n"}</text>
            <div>

              <input ref={(ref) => { this.fileName = ref; }} />
            </div>
            <br />
            <div>
              <button>Upload</button>
            </div>
            <image source={this.state.imageURL} alt="img" />
          </form>
        );
      }
}

export default Main; 

标签: javascriptreactjs

解决方案


import React, { useState } from "react";

const Main = () => {
  const [imageURL, setImageURL] = useState("");
  const [file, setFile] = useState({});
  const [fileName, setFileName] = useState("");

  const handleUploadImage = (ev) => {
    ev.preventDefault();

    const data = new FormData();
    data.append("file", file);
    data.append("filename", fileName);

    fetch("http://localhost:8000/upload", {
      method: "POST",
      body: data,
    }).then((response) =>
      response
        .json()
        .then((body) => setImageURL(`http://localhost:8000/${body.file}`))
    );
  };

  return (
    <form>
      <div>
        <text>{"\n\n"}</text>
        <input onChange={(e) => setFile(e.target.files[0])} type="file" />
      </div>
      <text>{"\n\n"}</text>
      <div>
        <input onChange={(e) => setFileName(e.target.value)} />
      </div>
      <br />
      <div>
        <button onClick={handleUploadImage}>Upload</button>
      </div>
      <img src={imageURL} alt="img" />
    </form>
  );
};

export default Main;

推荐阅读