首页 > 解决方案 > 使用 ReactJS 上传旋转图像预览

问题描述

我是 ReactJS 的新手,我正在尝试使用 ReactJS 上传旋转的图像预览。我跟着这个stackoverflow问题:

https://stackoverflow.com/questions/44530791/rotating-image-preview-with-reactjs

我能够集成,但我真的很困惑如何更新图像状态和上传。

我找不到关于这种情况的任何信息,我也尝试整合上传裁剪图像的方式,但我无法处理它。

这就是我通过 Dropzone 获取图像的方式:

<Label as="label" htmlFor="upload">
  <div  className={styles.card}>
     <Dropzone
         onDrop={this.onImageDrop}
         accept="image/*"
         multiple={false}
      >
      {({ getRootProps, getInputProps }) => {
          return (
            <div {...getRootProps()}>
               <input {...getInputProps()} />
               {
                 <p>
                 Upload your profile picture.
                 </p>
                }
              </div>
           );
        }}
        </Dropzone>

     </div>
     </Label>
     {this.state.uploadedFile === null ? '' : (
        <div>
          <RotateImage src={this.state.uploadedFile} />
        </div>
     )}

这就是我更新 profile_image 的方式:

 onImageDrop(files) {
    this.setState({
      profile_image: files[0],
      uploadedFile: URL.createObjectURL(files[0]),
    });
  }

这是它的提交部分(我将它传递给redux):

onSubmit(e) {

  e.preventDefault();

  const {
    profile_image
  } = this.state;

  fileUrl.append('profile_image', profile_image);

  this.props.createProfile(fileUrl, this.props.history);
}

这是我的构造函数:

constructor(props) {
    super(props);
    const { auth } = this.props;
    const { location } = auth;
    this.state = {
      uploadedFile: null
    };

    this.onImageDrop = this.onImageDrop.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
  }

这是我从其他 stackoverflow 问题中获得的 RotateImage 组件(所有学分都归功于他们):

import React, { Component } from 'react';

class rotateImage extends Component{
  constructor(props){
    super(props);
    this.state = {
      rotation: 0
    }

    this.rotate = this.rotate.bind(this);
    this.rotateleft = this.rotateleft.bind(this);
  }

  rotate(){
    let newRotation = this.state.rotation + 90;
    if(newRotation >= 360){
      newRotation =- 360;
    }
    this.setState({
      rotation: newRotation,
    })
  }

  rotateleft(){
    let newRotation = this.state.rotation - 90;
    if(newRotation >= 360){
      newRotation =- 360;
    }
    this.setState({
      rotation: newRotation,
    })
  }

  render(){
    const { rotation } =  this.state;
    return <div><img style={{transform: `rotate(${rotation}deg)`}} src={this.props.src} width="200" />
      <input onClick={this.rotateleft} type="button" value="left" />
      <input onClick={this.rotate} type="button" value="right" />
    </div>
  }
}

export default rotateImage;

我正在尝试上传旋转的图像,但我真的不知道如何更新旋转的图像状态。任何帮助,将不胜感激。

标签: javascriptreactjs

解决方案


推荐阅读