首页 > 解决方案 > 过渡不适用于 React useState hook 和 styled-component

问题描述

当我单击按钮时,转换会立即发生。如何添加平滑的进出过渡?当按钮处于焦点时,我希望整体滑动顺畅。


  const [margin, setMargin] = useState("-100vw");
  
  const setStyle = (margin) => {
    setMargin(margin);
  };

  const Box = styled.span`
    display: block;
    width: 150vw;
    margin-top: 0;
    height: 0;

    margin-left: ${margin};

    transition: all 0.8s 0.2s ease-in-out;
  `;
 

  return (
    <Box>
      <Wrapper>
        {children}
        <p>page contents</p>
        <button onMouseEnter={() => setStyle("-100vw")}>Change</button>
      </Wrapper>

      <TriangleLeft>
        <Closer>
          <button onMouseEnter={() => setStyle("0")}>Change</button>
        </Closer>
      </TriangleLeft>
    </Box>
  );
};


我不确定这是否是css的问题或我如何处理钩子......

标签: cssreactjsreact-hooks

解决方案


我看看你的代码,你只需要做一些改变:

从 Field 组件中删除所有样式化的组件,如下所示:

  const TriangleLeft = styled.span`
    ....
  `;

  const Box = styled.span`
    ....
  `;

  const Wrapper = styled.span`
    ....
  `;

  const Closer = styled.span`
    ....
  `;

  const Field = ({ children }) => {
  
    const [margin, setMargin] = useState("-100vw");
    const setStyle = (margin) => {
      setMargin(margin);
    };

    return .....
  }

此外,在您的 Box 样式中,您的 margin-left 应该是:

/* Completed Style: */
const Box = styled.span<BoxProps>`
 display: block;
 width: 150vw;
 margin-top: 0;
 height: 0;

 /* Here you are getting the prop margin and setting it to margin-left */
 margin-left: ${props => props.margin};

 transition: all 0.8s 0.2s ease-in-out;
`;

最后在您的 Box 标签中:

return (
    // Here you are saying that Box has a custom prop named margin and setting it with margin state.
    <Box margin={margin}>
      <Wrapper>
        {children}
      .....

你可以在这里查看


推荐阅读