首页 > 文章列表 > 在 React 中使用 CSS 拖放图像

在 React 中使用 CSS 拖放图像

477 2025-02-20

在 React 中使用 CSS 拖放图像

使用React和纯CSS构建一个简单的图像拖放功能,无需任何外部库。本教程将引导您完成创建这个功能的步骤。

步骤一:项目设置

首先,创建一个新的React项目。可以使用create-react-app

npx create-react-app drag-and-drop

步骤二:基本结构

替换App.jsApp.css文件内容如下:

App.js:

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

function App() {
  return (
    <div className="App">
      <h2 className="heading">选择图片:</h2>
      <div className="image-area">
        <ImageContainer />
      </div>
    </div>
  );
}

export default App;

App.css:

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

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

步骤三:创建图像容器组件

创建一个名为ImageContainer.js的新文件,并添加以下代码:

ImageContainer.js:

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

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

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

    return (
        <div className="image-container">
            {url ? (
                <img alt="" className="image-view" src={url} />
            ) : (
                <div className="upload-container">
                    <p>拖放图片到这里</p>
                    <p>或</p>
                    <p>点击选择</p>
                    <input type="file" className="input-file" onChange={onChange} />
                </div>
            )}
        </div>
    );
};

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, 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;
}

.image-view {
    max-width: 100%;
    max-height: 100%;
}

步骤四:运行应用

在终端运行npm start启动应用程序。现在,您可以将图像拖放到容器中或点击“点击选择”按钮来选择图像。

本教程展示了如何使用React和纯CSS创建简单的图像拖放功能,无需额外依赖。 记住,这个例子只处理图像预览,并未实现真正的拖放移动功能。 要实现完整的拖放移动,需要使用JavaScript事件处理。