【问题标题】:How to make a styled component work with css transition?如何使样式化的组件与 css 过渡一起使用?
【发布时间】:2019-11-16 14:52:40
【问题描述】:

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

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

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

这里是代码框示例: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>
  );
}

【问题讨论】:

    标签: reactjs styled-components


    【解决方案1】:

    它不起作用,因为您在 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);
    

    【讨论】:

      猜你喜欢
      • 2018-03-17
      • 1970-01-01
      • 2022-01-25
      • 2018-10-17
      • 1970-01-01
      • 2017-09-19
      • 2023-01-18
      • 2021-08-22
      • 2023-03-08
      相关资源
      最近更新 更多