【问题标题】:Using React-Spring useSprings only on active button in array仅在数组中的活动按钮上使用 React-Spring useSprings
【发布时间】:2022-01-08 22:52:17
【问题描述】:

我正在尝试为活动框的位置变化设置动画。当用户单击该框时,我希望该框为顶部边缘更改设置动画,其余框保持在 0px。当用户更改活动框时,之前的活动框将返回 0px,新的活动框将获得 50px 的 margin-top。

我想我快到了,但我还没有设法让它发挥作用。如果有人能帮助我了解我做错了什么,我将不胜感激。

import { useSpring, useSprings, animated } from "react-spring";
import styled from "styled-components";

const Nav = () => {

  // Set Active Box
 const [activeBox, setActiveBox] = useState(0);

  const handleClick = (index) => {
    setActiveBox(index);
  };

// Boxes
  const boxes = [box1, box2, box3, box4];


// useSprings 
  const springs = useSprings(
    boxes.length,
    boxes.map((box, index) => ({
      marginTop: activeBox === index ? 50 : 0,
    }))
  );

  return (
    <NavContainer>
      {springs.map((prop, index) => (
        <StyledBox
          style={prop}
          key={index}
          onClick={() => handleClick(index)}
          currentActiveBox={activeBox === index}
        >
          <img src={boxes[index]} alt="" />
        </StyledBox>
      ))}
    </NavContainer>
  );
};

export default Nav;

const NavContainer = styled.div`
  position: absolute;
  bottom: 0;
  width: 200px;
  height: 75px;
`;

const StyledBox = styled.div`
  width: 25px;
  height: 25px;

  img {
    width: 100%;
    height: 100%;
  }

`;

谢谢!

【问题讨论】:

    标签: javascript reactjs react-spring


    【解决方案1】:

    问题是动画没有添加到样式组件中!

    const StyledBox = styled(animated.div)`
      width: 25px;
      height: 25px;
    
      img {
        width: 100%;
        height: 100%;
      }
    

    【讨论】:

      猜你喜欢
      • 2019-10-14
      • 2018-12-27
      • 1970-01-01
      • 2018-08-28
      • 2019-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-14
      相关资源
      最近更新 更多