【问题标题】:React functional component static propertyReact 功能组件静态属性
【发布时间】:2020-01-02 21:04:46
【问题描述】:

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

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)

有什么帮助吗?

【问题讨论】:

标签: reactjs typescript


【解决方案1】:

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

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

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

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

【讨论】:

  • @JohnnyZabala 我看错了,我以为他们有Panel.Fieldset: PanelFieldset, d'oh
  • 哦,我明白了!是的,在那种情况下你是对的,它不会是有效的 js。
  • 谢谢,但我遇到了同样的错误:FunctionComponent 类型上不存在属性“添加”
  • @SimoneConti 似乎不相关?在给出的示例中有Add 属性。
  • 是相关的。 React.Component&lt;Props&gt; 只能在 props 内定义键。 Fieldset 是函数本身的属性,而不是道具内部
【解决方案2】:

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

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

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

【讨论】:

    【解决方案3】:

    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;
    

    【讨论】:

    • 谢谢,我最终得到了: const Panel: React.FunctionComponent & { PanelFieldset: React.FunctionComponent }
    • 作为内联类型有相当多的内容,但我不会告诉你如何编写代码;)。很高兴它成功了,祝你项目的其余部分好运
    【解决方案4】:

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

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

    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

    【讨论】:

      猜你喜欢
      • 2019-12-15
      • 1970-01-01
      • 2021-01-08
      • 2020-01-04
      • 2019-03-24
      • 1970-01-01
      • 1970-01-01
      • 2023-01-20
      • 1970-01-01
      相关资源
      最近更新 更多