gpt4 book ai didi

reactjs - react 功能组件静态属性

转载 作者:搜寻专家 更新时间:2023-10-30 21:20:56 25 4
gpt4 key购买 nike

我有一个类组件,另一个类组件作为他的静态属性。现在换成函数式组件了,不知道怎么保持静态属性。

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;
}

但是我得到了错误:“FunctionComponent”类型上不存在属性“Fieldset”.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/types/components/Dropdown.d.ts

关于reactjs - react 功能组件静态属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57712682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com