React 功能组件静态属性

Sim*_*nti 21 typescript reactjs

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

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>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

现在,切换到功能组件:

const Panel: React.FunctionComponent<Props> = (props) => {
  Panel.Fieldset = PanelFieldset;
}
Run Code Online (Sandbox Code Playgroud)

但我收到错误:属性 'Fieldset' 在类型 'FunctionComponent'.ts(2339) 上不存在

有什么帮助吗?

oem*_*era 23

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

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

const PanelComponent: React.FC<Props> = (props) => {
 ...
}

export const Panel = Object.assign(PanelComponent, { PanelFieldset })
Run Code Online (Sandbox Code Playgroud)

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

如果你想显式地输入你的静态属性,扩展@Andrew 的答案, usingtypeof PanelFieldset应该更方便地输入你的组件。

type IPanel<P> = React.FunctionComponent<P> & {
  Fieldset: typeof PanelFieldset; // add this
}

const Panel: IPanel<Props> = (props) => {
}

Panel.Fieldset = PanelFieldset;
Run Code Online (Sandbox Code Playgroud)

来源: https : //github.com/react-bootstrap/react-bootstrap/blob/master/types/components/Dropdown.d.ts


Jam*_*mes 18

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

function Panel() {
}
// static props
Panel.Fieldset = PanelFieldset
Run Code Online (Sandbox Code Playgroud)

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

Panel.Fieldset: React.Component<Props> = PanelFieldset
Run Code Online (Sandbox Code Playgroud)


And*_*rew 9

React.FunctionComponent范围完全在 中key props,当您想要添加不在props键中的属性时,您发现它不起作用。为了正确键入它,您需要创建自己的类型并对其进行扩展。

之后,将其分配到函数之外

type IPanel<P> = React.FunctionComponent<P> & {
  Fieldset: any //whatever type it actually is
}

const Panel: IPanel<Props> = (props) => {
}

Panel.Fieldset = PanelFieldset;
Run Code Online (Sandbox Code Playgroud)


Joh*_*ala 5

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

// Bad
function A() {
  A.B = 'hello'
}

// Good
function A() {}
A.B = "Here we go."
Run Code Online (Sandbox Code Playgroud)