反应功能组件静态属性



我有一个类组件,另一个类组件作为他的静态属性。 现在我切换到函数组件,我不知道如何保留静态属性。

class Panel extends React.Component<Props> {
public static Fieldset = PanelFieldset;
}
class PanelFieldset extends React.Component<Props> {
...
}
class App extends React.Component<Props> {
public render() {
return (
<Panel>
<Panel.Fieldset>
...
</Panel.Fieldset>
</Panel>
)
}
}

现在,切换到功能组件:

const Panel: React.FunctionComponent<Props> = (props) => {
Panel.Fieldset = PanelFieldset;
}

但我收到错误: 属性"字段集"在类型"函数组件"上不存在。ts(2339(

有什么帮助吗?

使用隐式类型(最佳解决方案(

下面显示了一个不必显式键入静态属性的配置。我个人更喜欢这个而不是任何其他解决方案,因为它是最短和最干净的方法。

const PanelComponent: React.FC<Props> = (props) => {
...
}
export const Panel = Object.assign(PanelComponent, { PanelFieldset })

使用显式键入(以前的解决方案(

如果要显式键入静态属性,扩展@Andrew的答案,使用typeof PanelFieldset应该更方便地键入组件。

type IPanel<P> = React.FunctionComponent<P> & {
Fieldset: typeof PanelFieldset; // add this
}
const Panel: IPanel<Props> = (props) => {
}
Panel.Fieldset = PanelFieldset;

来源:https://github.com/react-bootstrap/react-bootstrap/blob/master/src/Dropdown.tsx#L230-L237

对于函数上的static属性,您可以在函数本身上声明它们,即

function Panel() {
}
// static props
Panel.Fieldset = PanelFieldset

在组件上设置 propType 时可以看到类似的方法。我假设在 TS 中看起来像:

Panel.Fieldset: React.Component<Props> = PanelFieldset
React.FunctionComponent

的范围纯粹在keyprops内,当您想要添加不在props键中的属性时,您发现该属性不起作用。为了正确键入它,您需要创建自己的类型并扩展它。

之后,将其分配给函数外部

type IPanel<P> = React.FunctionComponent<P> & {
Fieldset: any //whatever type it actually is
}
const Panel: IPanel<Props> = (props) => {
}
Panel.Fieldset = PanelFieldset;

Typescript 编译器告诉您正在使用函数中未定义的属性。将Panel.Fieldset = PanelFieldset;移到 de 功能之外。

// Bad
function A() {
A.B = 'hello'
}
// Good
function A() {}
A.B = "Here we go."

最新更新