如何在 framer-motion styled-component 上定义道具? (公益广告)

How to define props on framer-motion styled-component? (PSA)

公益广告:

(不是问题,但我在堆栈上没有看到任何答案,所以这就是答案。)

在包装动作的样式组件上定义道具,在使用 styled().

包装动作时如何定义它们有点令人困惑

如何根据样式组件定义道具docs

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)};
`;

如何在代码中定义道具没有动作:

import styled from "styled-components";

interface Props {
  height?: number;
}

const Container = styled.div<Props>`
  height: ${({ height }) => height};
`;

export default Container;

如何在代码中定义道具 with motion:

import { HTMLMotionProps, motion } from "framer-motion";
import styled from "styled-components";

/**
 * notice the props extend HTMLMotionProps<"div"> this is so all the default
 * props are passed such as `onClick`
 */
interface Props extends HTMLMotionProps<"div"> {
  height?: number;
}

//notice motion is called as a function instead of `motion.div`
const Container = styled(motion<Props>("div"))`
  height: ${({ height }) => height};
`;

export default Container;

问题是您对“动作 div”的定义有误。应该这样定义:


interface Props {
  height?: number;
}

// motion is an object that gives you access to the html tags (like the div)
const Container = styled(motion.div)<Props>`
  height: ${({ height }) => height};
`;

正如您在上面看到的,您只需要像任何其他组件一样将 motion.div 传入 styled 函数。