You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在基于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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 02:36:06