Gatsby | TypeScript | CSS | 动态组件加判断(动态css)

80 阅读1分钟

通过传入动态参数来决定某个css样式是否实现 eg:

定义 BGImg 组件

import React from 'react';
import { ImgBox } from './ImgBoxStyles'; // 假设 ImgBox 的样式定义在这个文件中

interface BGImgProps {
  src: string;
  alt: string;
  shouldScale?: boolean; 
}

export const BGImg: React.FC<BGImgProps> = ({ src, alt, shouldScale }) => {
  return <ImgBox src={src} alt={alt} shouldScale={shouldScale} />;
};

定义 ImgBox 样式

import styled from 'styled-components';

// 背景照片组件
export const ImgBox = styled.img<{ shouldScale?: boolean }>`
  width: 100%;
  height: 100%;
  object-fit: cover;
  position: absolute;
  margin: 0;

  // 动态样式基于传入的 shouldScale 属性
  ${({ shouldScale }) =>
    shouldScale &&
    `
    transition: transform 2s ease;
    &:hover {
      transform: scale(1.5);
    }
  `}
`;

使用示例

这样,当你在其他文件中使用 BGImg 组件时,可以通过 shouldScale 属性来控制是否启用缩放效果

import React from 'react';
import { BGImg } from './BGImgComponent'; // 假设 BGImg 组件定义在这个文件中

const ExampleComponent = () => {
  return (
    <div>
      {/* 没有缩放效果 */}
      <BGImg src="image1.jpg" alt="Image without scale" />

      {/* 有缩放效果 */}
      <BGImg src="image2.jpg" alt="Image with scale" shouldScale />
    </div>
  );
};

export default ExampleComponent;

说明

  • shouldScale 属性:在 BGImg 组件中添加一个可选的 shouldScale 属性,并将其传递给 ImgBox
  • 动态样式:在 ImgBox 的样式中使用条件逻辑,只有当 shouldScale 为 true 时才应用缩放效果。
  • 组件使用:在使用 BGImg 组件时,通过传递 shouldScale 属性来控制是否启用缩放效果