【问题标题】:Transition not working with React useState hook and styled-component过渡不适用于 React useState hook 和 styled-component
【发布时间】:2020-08-21 02:10:21
【问题描述】:

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


  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 的问题还是我如何处理钩子...

【问题讨论】:

  • 沙箱中的代码与 sn-p 中的代码不匹配。

标签: css reactjs react-hooks


【解决方案1】:

我查看了您的代码,您只需要进行一些更改:

从 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}
      .....

您可以查看here

【讨论】:

    猜你喜欢
    • 2020-03-19
    • 2021-10-23
    • 2021-08-05
    • 2022-11-29
    • 2020-11-20
    • 2020-10-19
    • 2019-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多