如何使带样式的组件与 css 过渡一起使用?

How to make a styled component work with css transition?

该应用程序由 2 个蓝色方块和一个按钮组成。

第一个方块是 html div,第二个方块是样式组件 div。他们应该在点击按钮后的 2 秒过渡期间在蓝色和红色之间切换。但是,只有 html div 的方块会考虑过渡持续时间。带样式的组件会立即更改颜色。

是否可以让它工作,以便样式化的组件尊重过渡持续时间?

这里是codesandbox的例子:https://codesandbox.io/s/styled-component-transition-jcnom

function App() {
  const [red, setRed] = React.useState(false);
  function handleClick() {
    setRed(v => !v);
  }
  const styledCss =
    red &&
    css`
      background-color: red;
      transition: background-color 2s linear;
    `;
  const StyledSquare = styled.div`
    color: white;
    margin: 10px;
    width: 100px;
    height: 100px;
    background-color: blue;
    transition: background-color 2s linear;
    ${styledCss};
  `;
  const classes = red ? "red sq" : "sq";

  return (
    <div className="App">
      <div className={classes}>html div</div>
      <StyledSquare>styled component</StyledSquare>
      <button onClick={handleClick}>Click</button>
    </div>
  );
}

它不起作用,因为您在 App 功能中有您的样式组件。每次重新渲染都会再次声明,因此不会发生转换。只需将带样式的组件移到功能之外即可修复它。我将此处的道具传递给样式组件以更改颜色。

import React from "react";
import ReactDOM from "react-dom";
import styled, { css } from "styled-components";

import "./styles.css";

const StyledSquare = styled.div`
color: white;
margin: 10px;
width: 100px;
height: 100px;
background-color: ${props => props.red ? "red": "blue"};
transition: background-color 2s linear;
`;

function App() {
  const [red, setRed] = React.useState(false);
  function handleClick() {
    setRed(!red);
  }

  return (
    <div className="App">
      <StyledSquare red={red}>styled component</StyledSquare>
      <button onClick={handleClick}>Click</button>
    </div>
  );
}

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