使用typescript和react在这里
- 获取变量
const dib = 'display: inline-block;'
- 创建哑组件
export const FaGit = () => <i className="fa-brands fa-github"></i>
- 用
dib
样式扩展这个愚蠢的组件
export const GitIcon = styled(FaGit)(dib)
- 此时出现错误
TS2769: No overload matches this call.
Overload 1 of 3, '(first: TemplateStringsArray): StyledComponent<() => Element, any, {}, never>', gave the following error.
Argument of type 'string' is not assignable to parameter of type 'TemplateStringsArray'.
Overload 2 of 3, '(first: TemplateStringsArray | CSSObject | InterpolationFunction<ThemeProps<any>>, ...rest: Interpolation<ThemeProps<any>>[]): StyledComponent<...>',
gave the following error.
Argument of type 'string' is not assignable to parameter of type 'TemplateStringsArray | CSSObject | InterpolationFunction<ThemeProps<any>>'.
Overload 3 of 3, '(first: TemplateStringsArray | CSSObject | InterpolationFunction<ThemedStyledProps<{} & object, any>>, ...rest: Interpolation<...>[]): StyledComponent<...>', gave the following error.
Argument of type 'string' is not assignable to parameter of type 'TemplateStringsArray | CSSObject | InterpolationFunction<ThemedStyledProps<{} & object, any>>'.
那么,dib应该是什么类型,或者它应该是什么样子?
styled(SomeComp)(...)
函数不接受string
。它需要一个TemplateStringsArray
。虽然这看起来像一个字符串,但实际上是完全不同的。
请看下面的示例,看看这样一个模板函数是如何工作的:
function template(values: TemplateStringsArray, ...keys: any[]) {
console.log(typeof values, values, keys)
}
const dib = 'display: inline-block;' // <= string
const dib2 = `display: inline-block;` // <= still a string
template(dib) // error... function does not take a string
template(dib2) // still an error
template`hello ${1} world` // working! this isn't a string, it's a tagged template
template`${dib}` // how you might get your string into a s-c template
作为题外话,有样式的组件文档给出了以下关于React组件样式化的建议:
如果你使用style (MyComponent)标记,而MyComponent没有渲染传入的className道具,那么就不会应用任何样式。为了避免这个问题,确保你的组件将传入的className附加到一个DOM节点
…所以除非你把className:string
属性传递给HTML元素,否则你的FaGit
组件不会响应有样式的组件。
你可以这样做:
export const FaGit: React.FC<{className?: string}> =
({className}) => <i className={`fa-brands fa-github ${className ?? ''}`}></i>
把这些放在一起,你应该能够:
export const GitIcon = styled(FaGit)`${dib}`;