MST

星途 面试题库

面试题:React中利用Props实现复杂动画样式的动态控制

在一个React应用中,有一个可拖动的元素组件。要求通过props传入`dragSpeed`(代表拖动速度)和`dragDirection`(代表拖动方向,如'horizontal'或'vertical'),基于这些props实现元素在页面上根据指定速度和方向进行平滑动画拖动的效果,使用CSS动画或React动画库(如React - spring)来完成,阐述整体思路并编写核心代码。
36.6万 热度难度
前端开发React

知识考点

AI 面试

面试题答案

一键面试

整体思路

  1. 使用React - spring库:它提供了简单且强大的方式来创建动画。通过监听鼠标事件(如mousedownmousemovemouseup),根据dragSpeeddragDirection来计算元素的位置变化,并通过动画库将这些变化以平滑的动画呈现。
  2. CSS动画:同样监听鼠标事件,计算位置变化,然后通过CSS的transition属性来实现平滑过渡效果。这里以React - spring为例。

核心代码

import React, { useState } from 'react';
import { useSpring, animated } from'react-spring';

const DraggableElement = ({ dragSpeed, dragDirection }) => {
  const [isDragging, setIsDragging] = useState(false);
  const [startPosition, setStartPosition] = useState({ x: 0, y: 0 });
  const [currentPosition, setCurrentPosition] = useState({ x: 0, y: 0 });

  const handleMouseDown = (e) => {
    setIsDragging(true);
    setStartPosition({ x: e.pageX, y: e.pageY });
    setCurrentPosition({ x: currentPosition.x, y: currentPosition.y });
  };

  const handleMouseMove = (e) => {
    if (isDragging) {
      const dx = e.pageX - startPosition.x;
      const dy = e.pageY - startPosition.y;
      if (dragDirection === 'horizontal') {
        setCurrentPosition({ x: currentPosition.x + dx * dragSpeed, y: currentPosition.y });
      } else {
        setCurrentPosition({ x: currentPosition.x, y: currentPosition.y + dy * dragSpeed });
      }
    }
  };

  const handleMouseUp = () => {
    setIsDragging(false);
  };

  const springProps = useSpring({
    x: currentPosition.x,
    y: currentPosition.y
  });

  return (
    <animated.div
      onMouseDown={handleMouseDown}
      onMouseMove={handleMouseMove}
      onMouseUp={handleMouseUp}
      style={{
        position: 'absolute',
        left: springProps.x,
        top: springProps.y,
        backgroundColor: 'lightblue',
        width: '50px',
        height: '50px'
      }}
    />
  );
};

export default DraggableElement;

在上述代码中:

  1. useState用于管理拖动状态(isDragging)、起始位置(startPosition)和当前位置(currentPosition)。
  2. handleMouseDown事件记录起始位置并设置拖动状态为true
  3. handleMouseMove事件根据dragDirectiondragSpeed更新当前位置。
  4. handleMouseUp事件结束拖动状态。
  5. useSpring用于创建平滑动画,将当前位置应用到元素的lefttop属性上。