每次在 styled-components 中使用钩子更改 props.children 时做动画

Do animate when every time props.children is changed in styled-components using hooks

我想在每次 props.children 更改时在名为 Counter 的钩子组件中触发我的动画 styled-components v4 但我不知道如何实现我的代码。

这是我的代码。

import React, { useState } from 'react';
import styled, { css, keyframes } from 'styled-components';

const highlight = keyframes`
  25% {
    transform: scale(1.3);
  }

  100% {
    transform: scale(1.0);
  }
`;

const highlightAnimation = css`
  animation: ${highlight} 1s ease;
`;

const Circle = styled.div`
  // ...other attributes
  ${highlightAnimation}
`;

const Counter = ({ children, color, status }) => {
  return (
    <Circle color={color} status={status}>
      {children}
    </Circle>
  );
};

export default Counter;

首次渲染时仅设置一次动画。

我认为这是 virtualDOM 中类似渲染的差异算法的问题。

当 children 发生变化时,它不会 re-render。它只是更改文本而不是 re-render

如果您想触发重新渲染,因此将应用一个新的动画,您只需向您的组件添加一个 key,其中包含您希望组件在更改时重新渲染的值。

 <Circle color={color} status={status} key={`${color}-${status}`}>

看看 React 在协调方面是如何工作的。

https://reactjs.org/docs/reconciliation.html