首页 > 解决方案 > 使用 styled-components 进行样式设置时,输入 React Components 的最佳方法是什么

问题描述

我正在将一个项目迁移到 Typescript。我有一个使用 styled-components 设置样式的组件,我需要在其他组件上使用 styled-components 覆盖它。我的组件看起来像这样。

该组件旨在渲染图像,如果图像不存在,则返回使用 styled-components 样式的 Fallback 元素。

import React, { useState } from 'react'
import styled from 'styled-components'

export const Fallback = styled.div`
    padding-bottom: 56%; /* 16/9 ratio */
    background-color: #e5e5e5;
`

export const Image = styled.img`
    image-rendering: pixelated;
    image-rendering: crisp-edges;
`

interface ImageWithFallbackProps {
    src: string
    alt: string
    fallback: typeof Fallback
}

const ImageWithFallback = ({
    src,
    alt,
    fallback = Fallback,
    ...props
}: ImageWithFallbackProps): React.ReactNode => {
    const [error, setError] = useState(false)
    const FallbackElement: React.FC = fallback

    if (error) return <FallbackElement />

    return <Image src={src} alt={alt} {...props} onError={() => setError(true)} />
}

export default ImageWithFallback

而且,我在另一个组件上使用它。

const Content: AnyStyledComponent = styled.div`
    /* styles */
`

Content.Text = styled.div`      
    font-weight: bold;
    flex: 1;
    text-align: left;
`

Content.Image = styled(ImageWithFallback)`
    flex: 1;
    max-width: 80px;
    align-self: baseline;
`

Content.Fallback = styled(Fallback)`
    width: 80px;
    padding-bottom: 54px;
`

但是我在这样定义 Content.Image 时遇到错误Content.Image = styled(ImageWithFallback)。错误代码是 ts(2769)。我该如何解决这个问题?

标签: reactjstypescriptstyled-components

解决方案


推荐阅读