className 属性的 React + TypeScript 用法 [英] React + TypeScript usage of className prop
问题描述
在自定义组件中键入和使用 className
属性的正确方法是什么?我曾经能够做到这一点:
What is the correct way to type and use the className
prop in a custom component? I used to be able to do this:
class MyComponent extends React.Component<MyProps, {}> {
...
}
然后通过以下方式使用我的组件:
and then use my component via:
<MyComponent className="my-class" />
请注意,我不会在 MyProps
中定义 className
,尽管之前已键入 React 以支持这种用法.
Note that I would not define className
in MyProps
, though React was previously typed to support this usage.
现在,我现在看到了这个类型错误:
Now, I am now seeing this type error:
Property 'className' does not exist on type 'IntrinsicAttributes &
IntrinsicClassAttributes<Component<{}, ComponentState>> & Readonly<{
childr...'
定义/键入组件的正确方法是什么,以允许我在使用组件时使用 className
?
What is the correct way to define / type my component that will allow me to use className
when using my component?
推荐答案
您可以使用 HTMLAttributes
类型,例如:
You can use the HTMLAttributes
type, for example:
class MyComponent extends React.Component<MyProps & React.HTMLAttributes<HTMLDivElement>, {}> {
render() {
return <div className={ this.props.className }>My Div</div>
}
}
这样您就可以传递 html 元素可能需要的任何属性.
That way you can pass any of the properties that a html element might need.
如果您只需要 className
属性,那么您可以这样做:
If you only need the className
property then you can do this:
class MyComponent extends React.Component<MyProps & { className: string }, {}> {
render() {
return <div className={ this.props.className }>My Div</div>
}
}
或者只是将其添加到您的 MyProps
类型中.
Or simply add it to your MyProps
type.
这篇关于className 属性的 React + TypeScript 用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!