首页 > 解决方案 > 如何在 React 中拖动带有动画的组件

问题描述

我正在尝试拖动其 css 具有变换动画的组件。但它无法正常工作。组件只是根据动画移动,无法拖动。有没有办法实现拖拽功能?

import * as React from "react";
import {
  theComponent
} from "../style.css";
import Draggable from "react-draggable";

class DragMe extends React.Component {
  render() {
    return (
      <Draggable
        axis="both"
        handle=".handle"
        defaultPosition={{ x: 0, y: 0 }}
        position={null}
        grid={[25, 25]}
        scale={1}
        onStart={this.handleStart}
        onDrag={this.handleDrag}
        onStop={this.handleStop}
      >
        <div className={theComponent + " handle"}>
          <p>Drag Me!</p>
        </div>
      </Draggable>
    );
  }
}
. theComponent{
  animation: moveAnimation 3.5s infinite;
}

@keyframes moveAnimation {
  0%,
  100% {
    transform: translate(-200%, 20%);
  }
  50% {
    transform: translate(-200%, 25%);
  }
}

标签: javascriptcssreactjs

解决方案


如果您将 css 动画从 更改 transformtop, left,则内联样式transform将起作用并被拖动。尝试像这个例子一样重写css

.theComponent {
  position: relative;
  animation: moveAnimation 3.5s infinite;
}
@keyframes moveAnimation {
  0%,
  100% {
    top: 5px;
  }
  50% {
     top: 0px;
  }
}

推荐阅读