如何在基于framer-motion封装的styled-component上定义props?
PSA:
(这不是提问,我在Stack Overflow上未找到相关解答,因此在此分享解决方案。)
很多开发者在给封装了motion的styled-component定义props时,都不清楚使用styled()包裹motion时该如何声明这些属性。
以下是styled-components官方给出的props定义规范:
import styled from 'styled-components'; import Header from './Header'; interface TitleProps { readonly isActive: boolean; } const Title = styled.h1<TitleProps>` color: ${(props) => (props.isActive ? props.theme.colors.main : props.theme.colors.secondary)}; `;
未接入motion时的props定义代码示例:
import styled from "styled-components"; interface Props { height?: number; } const Container = styled.div<Props>` height: ${({ height }) => height}; `; export default Container;
接入framer-motion后的正确props定义代码示例:
import { HTMLMotionProps, motion } from "framer-motion"; import styled from "styled-components"; /** * 注意这里的props继承了HTMLMotionProps<"div">,可以保证所有默认属性(比如`onClick`)都能正常传递 */ interface Props extends HTMLMotionProps<"div"> { height?: number; } // 注意这里motion是作为函数调用的,不是用`motion.div`的写法 const Container = styled(motion<Props>("div"))` height: ${({ height }) => height}; `; export default Container;
内容的提问来源于stack exchange,提问作者Shawn
相关产品推荐
相关产品推荐

