className 属性的 React + TypeScript 用法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44369706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:36:35  来源:igfitidea点击:

React + TypeScript usage of className prop

reactjstypescript

提问by mattnedrich

What is the correct way to type and use the classNameprop in a custom component? I used to be able to do this:

className在自定义组件中键入和使用prop的正确方法是什么?我曾经能够做到这一点:

class MyComponent extends React.Component<MyProps, {}> {
  ...
}

and then use my component via:

然后通过以下方式使用我的组件:

<MyComponent className="my-class" />

Note that I would not define classNamein MyProps, though React was previously typed to support this usage.

请注意,我不会定义classNamein MyProps,尽管之前已键入 React 以支持此用法。

Now, I am now seeing this type error:

现在,我现在看到此类型错误:

Property 'className' does not exist on type 'IntrinsicAttributes & 
IntrinsicClassAttributes<Component<{}, ComponentState>> & Readonly<{ 
childr...'

What is the correct way to define / type my component that will allow me to use classNamewhen using my component?

定义/键入我的组件的正确方法是什么,以便我className在使用我的组件时使用它?

回答by Nitzan Tomer

You can use the HTMLAttributestype, for example:

您可以使用该HTMLAttributes类型,例如:

class MyComponent extends React.Component<MyProps & React.HTMLAttributes<HTMLDivElement>, {}> {
    render() {
        return <div className={ this.props.className }>My Div</div>
    }
}

That way you can pass any of the properties that a html element might need.

这样您就可以传递 html 元素可能需要的任何属性。

If you only need the classNameproperty then you can do this:

如果您只需要该className属性,则可以执行以下操作:

class MyComponent extends React.Component<MyProps & { className: string }, {}> {
    render() {
        return <div className={ this.props.className }>My Div</div>
    }
}

Or simply add it to your MyPropstype.

或者简单地将它添加到您的MyProps类型中。

回答by Kherel

For someone who are looking solution for functional components, as I was.

对于像我一样正在寻找功能组件解决方案的人。

type Props = {
  pathname?: string
}

const MyComponent: React.FC<Props> = (props) => (
  <div className={props.className}>{props.children}</div>
)

export default MyComponent

or if you want to declare interface separately:

或者如果你想单独声明接口:

interface OnlyClassNameInterface extends React.FC<{className: string}> {}

const MyComponent: OnlyClassNameInterface = (props) => (
  <div className={props.className}>{props.children}</div>
)

export default MyComponent

and you can move interface to another file

你可以将界面移动到另一个文件

import React from 'react'

type MixProps<P> = P & {className?: string}

export interface OnlyClassNameInterface<P = {}> extends React.FC<MixProps<P> {}