如何在 React 中实现图像拖放

**如何仅使用 CSS 在 React 中实现图像拖放**

React 因构建交互式 UI 而广受认可。在本教程中,我们将指导您仅使用 CSS 在 React 中创建图像拖放功能。

步骤 1:设置你的 React 项目

首先设置您的 React 项目。您可以使用“create-react-app”轻松进行设置。

npx create-react-app drag-and-drop

第 2 步:更新 App.js 和 App.css

接下来,修改“App.js”文件以创建图像和标题的容器。

import './App.css';

function App() {
  return (
    

Select Image:

); } export default App;

在 `App.css` 中,设置页面样式:

.App {
  text-align: center;
  width: 100vw;
  height: 100vh;
}

.heading {
  font-size: 32px;
  font-weight: 500;
}

步骤3:创建ImageContainer组件

创建一个新文件“ImageContainer.js”并定义一个基本的拖放容器。

import React from 'react';

const ImageContainer = () => {
  return (
    
); }; export default ImageContainer;

在“ImageContainer.css”中设置此容器的样式:

.image-container {
  width: 60%;
  height: 90%;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px dashed rgba(0, 0, 0, .3);
}

步骤 4:添加图片上传功能

通过文件输入和文本说明为用户增强“ImageContainer”。

import React from 'react';
import './ImageContainer.css';

const ImageContainer = () => {
  const [url, setUrl] = React.useState('');

  const onChange = (e) => {
    const files = e.target.files;
    if (files.length > 0) {
      setUrl(URL.createObjectURL(files[0]));
    }
  };

  return (
    

Drag & Drop here

or

Click

); }; export default ImageContainer;

并设置“upload-container”的样式:

.image-container {
  width: 60%;
  height: 90%;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px dashed rgba(0, 0, 0, .3);
}

.upload-container {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: white;
}

.upload-container > p {
  font-size: 18px;
  margin: 4px;
  font-weight: 500;
}

.input-file {
  display: block;
  border: none;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  opacity: 0;
}

步骤 5:预览图像

修改组件以有条件地渲染上传的图像或拖放区域。

import React from 'react';
import './ImageContainer.css';

const ImageContainer = () => {
  const [url, setUrl] = React.useState('');

  const onChange = (e) => {
    const files = e.target.files;
    if (files.length > 0) {
      setUrl(URL.createObjectURL(files[0]));
    }
  };

  return (
    
{url ? ( ) : (

Drag & Drop here

or Browse

)}
); }; export default ImageContainer;

步骤 6:导入并运行应用程序

最后,将“ImageContainer”导入“App.js”并运行应用程序。

import './App.css';
import ImageContainer from './ImageContainer';

function App() {
  return (
    

Select Image:

); } export default App;

现在您可以运行该应用程序并享受使用 React 和 CSS 编写图像拖放功能。

本教程介绍如何使用 React 为图像设置基本的拖放区域、利用文件输入和 CSS 进行样式设置以及处理图像预览。