【问题标题】:How to add functions inside styled-components如何在样式组件中添加功能
【发布时间】:2021-08-12 16:36:47
【问题描述】:

我将 open 一个 prop 传递给一个布尔值的组件

我想添加一个 setTimeout 函数来隐藏组件,但它显示语法错误

Timeout' is not assignable to parameter of type 
'Interpolation<ThemedStyledProps<Pick<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, 
HTMLDivElement>, "key" | keyof HTMLAttributes<HTMLDivElement>> 

这是我尝试过的

const DrawerContent = styled.div<{ open: boolean; visible?: any }>`
  transition: 0.3s all;
  ${({ open, visible }) =>
    open
      ? css`
          display: flex;
          width: 200px;
          height: 100px;
          background-color: brown;
          position: absolute;
          top: 0;
        `
      : setTimeout(() => { // i want to add this line
          css`
            display: none;
          `;
        }, 200)}
`;

【问题讨论】:

    标签: reactjs typescript styled-components


    【解决方案1】:

    您无法从 setTimeout 回调函数中获取返回值。如果你想在一段时间后隐藏节点,你应该使用keyframes

    const hide = keyframes`
        to {
            width:0;
            height:0;
            overflow:hidden;
        }
    `;
    
    const DrawerContent = styled.div`
      transition: 0.3s all;
      ${({ open, visible }) =>
        open &&
        css`
          display: flex;
          width: 200px;
          height: 100px;
          background-color: brown;
          position: absolute;
          top: 0;
          animation: ${hide} 0s ease-in 2s forwards;
        `}
    `;
    

    另一种解决方案是将timeout 函数移到DrawerContent 组件之外:

    const DrawerContent = styled.div`
      transition: 0.3s all;
      ${({ open, visible }) =>
        open &&
        css`
          display: flex;
          width: 200px;
          height: 100px;
          background-color: brown;
          position: absolute;
          top: 0;
        `}
    `;
    
    function App () {
      const [show, setShow] = useState(true);
    
      useEffect(() => {
        let timeout;
        if (show) {
          timeout = setTimeout(() => {
            setShow(false);
          }, 2000);
        }
        return () => clearTimeout(timeout);
      }, [show]);
      return (
        <>
          <div>
            <DrawerContent open={show} visible />
          </div>
        </>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-13
      • 2011-08-27
      • 2020-12-26
      • 2018-03-17
      • 2021-01-25
      • 2022-01-27
      • 2021-04-21
      相关资源
      最近更新 更多