反应功能组件的静态属性

时间:2019-08-29 14:46:33

标签: reactjs typescript

我有一个类组件,而另一个类组件是他的静态属性。 现在,我切换到一个功能组件,但我不知道如何保留静态属性。

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

但是我得到了错误: 属性“ Fieldset”在“ FunctionComponent”类型上不存在。ts(2339)

有帮助吗?

4 个答案:

答案 0 :(得分:18)

使用隐式键入(最佳解决方案)

以下显示了一种方法,您不必显式键入静态属性。我个人比其他任何解决方案都更喜欢此方法,因为它是最短,最简洁的方法。

<script type="text/javascript">
    function formatSearch(item) {
        var selectionText = item.text.split("|");
        var $returnString = $('<span>' + selectionText[0] + '</br><b>' + selectionText[1] + '</b></br>' + selectionText[2] +'</span>');
        return $returnString;
    };
    function formatSelected(item) {
        var selectionText = item.text.split("|");
        var $returnString = $('<span>' + selectionText[0].substring(0, 21) +'</span>');
        return $returnString;
    };
    $('.select2').select2({
        templateResult: formatSearch,
        templateSelection: formatSelected
    });
</script>

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

如果要显式键入静态属性,请使用const PanelComponent: React.FC<Props> = (props) => { ... } export const Panel = Object.assign(PanelComponent, { PanelFieldset }) 来扩展@Andrew的答案,以便键入组件更为方便。

typeof PanelFieldset

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

答案 1 :(得分:4)

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

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

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

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

答案 2 :(得分: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;

答案 3 :(得分:2)

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

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

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