css - 过渡不适用于 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的问题或我如何处理钩子......
解决方案
我看看你的代码,你只需要做一些改变:
从 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}
.....
你可以在这里查看。
推荐阅读
- angular - 使用库在 Angular 中对 URL 查询参数(查询值作为某个 URL)进行编码
- python - 从文件夹中读取所有图像和相应的蒙版并在原始图像上绘制计数并保存在python的文件夹中
- java - 默认位置如何工作?/ 什么是默认监视器?
- java - 白色填充/边框
- django - 在 Django 模板中获取查询集中的值
- python - 用Python读取一个excel文件,在不改变样式的情况下进行修改
- javascript - 在以角度上传到firebase之前调整大小/压缩所选图像
- nearprotocol - 小数位显示不正确
- r - 我将如何查找范围内的值:R 中的 VLOOKUP
- swift - Swift:如何使用 Combine 执行并发 API 调用