Как определить реквизит для компонента, стилизованного под фреймер-движение? (СРП)

#reactjs #typescript #styled-components #typescript-generics #framer-motion

Вопрос:

СРП:

(это не вопрос, но я не видел никаких ответов на этот вопрос в стеке, так что вот ответ.)

Определите реквизиты для стилизованных компонентов, которые обертывают движение, это немного сбивает с толку, как их определить при обертывании движения 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;
 

Ответ №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 .