如何在样式组件中使用 props

问题描述 投票:0回答:1

我想将一个url传递给一个组件,然后使用这个url来设置组件的背景图片。 我还想检查网址是否为空。

成分:


<BannerImg/>

css (styled) : 
`const BannerImg = styled.img`
background-image: url( // any url...);
z-index:9;
position:relative;
`

在搜索时,我发现了类似的东西(尽管根本不清楚)并解释为:

interface Props{
  url :string
}

const BannerImg=styled.img<Props>`
  background-image:url (${p=> p.url});
`

成分:

<BannerImg url={imageurl}/>

但这在组件的 url 中引发了错误

错误:

o overload matches this call. Overload 1 of 2, '(props: { title?: string | undefined; slot?: string | undefined; style?: CSSProperties | undefined; ref?: ((instance: HTMLImageElement | null) => void) | RefObject<...> | null | undefined; ... 277 more ...; url: string; } & { ...; } & { ...; }): ReactElement<...>', gave the following error. Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'. Overload 2 of 2, '(props: StyledComponentPropsWithAs<"img", any, Props, never, "img", "img">): ReactElement<StyledComponentPropsWithAs<"img", any, Props, never, "img", "img">, string | JSXElementConstructor<...>>', gave the following error. Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'.ts(2769) AesthCard.tsx(12, 3): The expected type comes from property 'url' which is declared here on type 'IntrinsicAttributes & { title?: string | undefined; slot?: string | undefined; style?: CSSProperties | undefined; ref?: ((instance: HTMLImageElement | null) => void) | RefObject<...> | null | undefined; ... 277 more ...; url: string; } & { ...; } & { ...; }' AesthCard.tsx(12, 3): The expected type comes from property 'url' which is declared here on type 'IntrinsicAttributes & { title?: string | undefined; slot?: string | undefined; style?: CSSProperties | undefined; ref?: ((instance: HTMLImageElement | null) => void) | RefObject<...> | null | undefined; ... 277 more ...; url: string; } & { ...; } & { ...; }

reactjs typescript styled-components
1个回答
0
投票

我在 Props 界面中将 url 属性设置为可选,因为您似乎希望能够处理未提供 URL 的情况。 我在样式化组件中使用了背景图像属性的模板文字,并添加了默认图像 URL(将“defaultImageUrl”替换为您要使用的实际默认 URL),以防 url 属性未定义。 这应该可以解决您遇到的 TypeScript 错误。确保您传递给 BannerImg 的 imageUrl 确实是一个字符串并且不是未定义的。如果它可能是未定义的,请确保在您的应用程序逻辑中适当地处理这种情况。

© www.soinside.com 2019 - 2024. All rights reserved.