-1

我是新来的反应。我在基于类的 reactjs 代码及其工作中有下面的照片上传器代码,但我希望它在基于反应功能的工作代码中。如果对同一个项目有任何其他建议以使用更正确和更清晰的代码,那么我将不胜感激。

代码如下:

import React, { Component } from 'react';
import './App.css';
export class App extends Component {
  state={
    profileImg:'https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_960_720.png'
  }
  imageHandler = (e) => {
    const reader = new FileReader();
    reader.onload = () =>{
      if(reader.readyState === 2){
        this.setState({profileImg: reader.result})
      }
    }
    reader.readAsDataURL(e.target.files[0])
  };
    render() {
    const { profileImg} = this.state
        return (
            <div className="page">
                <div className="container">
                    <h1 className="heading">Add your Image</h1>
                    <div className="img-holder">
                        <img src={profileImg} alt="" id="img" className="img" />
                    </div>
                    <input type="file" accept="image/*" name="image-upload" id="input" onChange={this.imageHandler} />
                    <div className="label">
          <label className="image-upload" htmlFor="input">
                        <i className="material-icons">add_photo_alternate</i>
                        Choose your Photo
                    </label>
          </div>
                </div>
            </div>
        );
    }
}

export default App;

我想要基于工作功能反应的组件代码。我希望将照片上传器集成到我的项目中。

4

1 回答 1

1
import React, { useState } from "react";
import "./App.css";

export default function App() {
  const [profileImage, setProfileImage] = useState(
    "https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_960_720.png"
  );

  const imageHandler = (e) => {
    const reader = new FileReader();
    reader.onload = () => {
      if (reader.readyState === 2) {
        setProfileImage(reader.result);
      }
    };
    reader.readAsDataURL(e.target.files[0]);
  };

  return (
    <>
      <div className="page">
        <div className="container">
          <h1 className="heading">Add your Image</h1>
          <div className="img-holder">
            <img src={profileImage} alt="" id="img" className="img" />
          </div>
          <input
            type="file"
            accept="image/*"
            name="image-upload"
            id="input"
            onChange={imageHandler}
          />
          <div className="label">
            <label className="image-upload" htmlFor="input">
              <i className="material-icons">add_photo_alternate</i>
              Choose your Photo
            </label>
          </div>
        </div>
      </div>
    </>
  );
}


查看此博客React 功能组件

于 2020-11-19T09:55:16.597 回答