2

我在 React 项目中使用Framer Motion作为动画库。我正在尝试使用when属性在子元素之后为父元素设置动画。它不起作用,因为ContentVariantsImgVariants正在同时运行。

密码箱

import React, { Component } from "react";
import ReactDOM from "react-dom";
import styled from "styled-components";
import { motion } from "framer-motion";

export const ContentVariants = {
  expanded: () => ({
    width: "150px",
    transition: {
      when: "afterChildren",
      duration: 2
    }
  }),
  collapsed: () => ({
    width: "50px",
    transition: {
      when: "afterChildren",
      duration: 2
    }
  })
};

export const Content = styled(motion.div)`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  background-color: burlywood;
  padding: 30px;
  height: 500px;
`;

export const ToggleBtn = styled.button`
  padding: 5px 10px;
  cursor: pointer;
  display: flex;
  width: auto;
  align-self: flex-end;
`;

export const ImgVariants = {
  expanded: {
    width: "100px",
    scale: 1,
    transition: {
      duration: 2
    }
  },
  collapsed: {
    scale: 0.5,
    transition: {
      duration: 2
    }
  }
};

const Img = styled(motion.img)``;

class App extends Component {
  state = {
    collapsed: false
  };

  toggle = () => {
    this.setState({ collapsed: !this.state.collapsed });
  };

  render() {
    const { collapsed } = this.state;
    return (
      <div>
        <Content
          initial={collapsed ? "collapsed" : "expanded"}
          animate={collapsed ? "collapsed" : "expanded"}
          variants={ContentVariants}
        >
          <Img
            src="https://picsum.photos/200/200"
            initial={collapsed ? "collapsed" : "expanded"}
            animate={collapsed ? "collapsed" : "expanded"}
            variants={ImgVariants}
          />
          <ToggleBtn onClick={this.toggle}>toggle</ToggleBtn>
        </Content>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

如果我更改when: "afterChildren"when: "beforeChildren"in ContentVariants,则没有任何区别。即使我删除when属性,动画也会同时运行。

4

2 回答 2

10

文档传播部分(https://www.framer.com/api/motion/animation/#propagation)说

如果运动组件有子组件,则变体的更改将通过组件层次结构向下流动。变体中的这些更改将向下流动,直到子组件定义其自己的动画属性。

您必须从元素中删除animate道具。Img

https://codesandbox.io/s/gallant-goldwasser-dwiz2

于 2019-11-29T21:16:53.947 回答
4

如果您为孩子设置动画,您的父母不会将其动画逻辑传递给它。因此,您必须从组件中删除initialandanimate属性<Img>

<Img
   src="https://picsum.photos/200/200"
   variants={ImgVariants}
/>

您可以从官方文档中查看此示例以供参考:https ://www.framer.com/api/motion/types/#orchestration.when

于 2019-11-29T21:22:31.517 回答