【问题标题】:How to define props on framer-motion styled-component? (PSA)如何在 framer-motion styled-component 上定义道具? (PSA)
【发布时间】:2021-12-13 18:17:22
【问题描述】:

PSA:

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

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

如何根据样式化组件定义props 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动作:

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;

【问题讨论】:

    标签: reactjs typescript styled-components typescript-generics framer-motion


    【解决方案1】:

    问题在于您错误地定义了“运动 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 函数。

    【讨论】:

      猜你喜欢
      • 2020-10-07
      • 2020-11-20
      • 2021-08-01
      • 2023-02-01
      • 2021-03-31
      • 2019-12-26
      • 2022-11-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多