繁体   English   中英

如何在 framer-motion 样式组件上定义道具? (PSA)

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

公益广告:

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

在包裹动作的样式组件上定义道具,当使用styled()包裹动作时如何定义它们有点令人困惑。

如何根据样式化组件文档定义道具

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;

如何在你的代码中用动作定义道具:

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函数中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM