在 React-Pose 中创建一个简单的动画

IT技术 reactjs animation react-hooks
2021-05-15 11:38:05

我在 React-Pose 中创建简单动画时遇到问题。这两个问题是

1)我无法让动画恢复到初始状态。当鼠标离开时,悬停变量会更改为 false,但动画不会变回来。

2)我无法操纵动画,我想要更长的持续时间,也许是缓出或其他什么,但它只是瞬间捕捉到悬停状态。

import React, { useState } from 'react';
import styled from 'styled-components';
import posed from 'react-pose';
import { render } from 'react-dom';

const UpFor = () => {

const [hovering, setHovering] = useState(false);

const HoverContainer = posed.div({
    hoverable: true
})

const Container = styled(HoverContainer)`
font-family: 'Baumans';
font-size: 220px;
display: flex;
cursor: pointer;
`

const Up = styled.div`
color: #81D6E3;`

const Four = styled.div`
color: #FF101F
`
const Fours = styled.div`
display: flex;
`
const MirroredFour = posed.div({
unhovered: {transform: 'rotatey(0deg)'},
hovered: {transform: 'rotateY(180deg)',
        transition: {
            type: 'tween',
            duration: '2s'
        }}
})

const SecondFour = styled(MirroredFour)`
color: #FF101F
position: absolute;
transform-origin: 67%;
`


return (
    <Container onMouseEnter={() => {setHovering({ hovering: true }), console.log(hovering)}}
               onMouseLeave={() => {setHovering({ hovering: false }), console.log(hovering)}}>
         <Up>Up</Up><Fours><Four>4</Four>
                <SecondFour pose={hovering ? "hovered" : "unhovered"}
                >4</SecondFour></Fours>
    </Container>)
}

export default UpFor
1个回答

您的代码有两个主要问题:

  1. duration似乎不支持像“2s”这样的字符串值。我把这个改成2000.
  2. 您在渲染函数中定义了组件(例如使用styled.div, posed.div)。这导致这些组件在每次重新渲染时都被 React 视为唯一的组件类型。这导致这些组件被卸载并重新安装每个渲染,这会阻止转换工作,因为元素没有改变——而是被不同类型的新组件替换。

下面是代码的工作版本,它将组件定义移到 render ( UpFor) 函数之外。您可以在提供的沙箱中使用它。

import React, { useState } from "react";
import styled from "styled-components";
import posed from "react-pose";

const Container = styled.div`
  font-family: "Baumans";
  font-size: 220px;
  display: flex;
  cursor: pointer;
`;

const Up = styled.div`
  color: #81d6e3;
`;

const Four = styled.div`
  color: #ff101f;
`;
const Fours = styled.div`
  display: flex;
`;
const MirroredFour = posed.div({
  unhovered: { transform: "rotateY(0deg)" },
  hovered: {
    transform: "rotateY(180deg)",
    transition: {
      type: "tween",
      duration: 2000
    }
  }
});

const SecondFour = styled(MirroredFour)`
color: #FF101F
position: absolute;
transform-origin: 67%;
`;

const UpFor = () => {
  const [hovering, setHovering] = useState(false);

  console.log("hovering", hovering);
  return (
    <Container
      onMouseEnter={() => {
        setHovering(true);
      }}
      onMouseLeave={() => {
        setHovering(false);
      }}
    >
      <Up>Up</Up>
      <Fours>
        <Four>4</Four>
        <SecondFour pose={hovering ? "hovered" : "unhovered"}>4</SecondFour>
      </Fours>
    </Container>
  );
};

export default UpFor;

编辑姿势