与TypeScript反应 - 在无状态函数中定义defaultProps

Mat*_*łło 21 typescript reactjs

我正在使用React和TypeScript,我已经创建了无状态函数.为了便于阅读,我从示例中删除了无用的代码.

interface CenterBoxProps extends React.Props<CenterBoxProps> {
    minHeight?: number;
}

export const CenterBox = (props: CenterBoxProps) => {
    const minHeight = props.minHeight || 250;
    const style = {
        minHeight: minHeight
    };
    return <div style={style}>Example div</div>;
};
Run Code Online (Sandbox Code Playgroud)

一切都很棒,这段代码工作正常.但有我的问题:我怎么可以定义defaultPropsCenterBox组件?

正如反应文档中提到的那样:

(...)它们是输入的纯函数变换,没有样板.但是,您仍然可以通过将它们设置为函数的属性来指定.propTypes和 .defaultProps,就像在ES6类上设置它们一样.(......)

它应该很容易:

CenterBox.defaultProps = {
    minHeight: 250
}
Run Code Online (Sandbox Code Playgroud)

但是此代码生成TSLint错误: error TS2339: Property 'defaultProps' does not exist on type '(props: CenterBoxProps) => Element'.

再说一遍:我怎样才能defaultProps在上面的堆栈中正确定义(React + TypeScript)?

Mat*_*łło 23

经过2个小时的寻找解决方案...... 它正在发挥作用.

如果要定义defaultProps函数定义行应该如下所示:

export const CenterBox: React.SFC<CenterBoxProps> = props => {
    (...)
};
Run Code Online (Sandbox Code Playgroud)

然后你可以定义道具,如:

CenterBox.defaultProps = { someProp: true }
Run Code Online (Sandbox Code Playgroud)

请注意,这React.SFC是别名React.StatelessComponent.

我希望这个问题(和答案)对某人有所帮助.确保您已安装最新的React类型.

  • 你可以添加一个更具体的例子来说明你如何使用defaultProps吗?感谢:D (2认同)

小智 21

我相信比 React 文档中描述的更好的方法是简单地使用 Javascript / Typescript 默认参数。

这里有一个答案:https : //stackoverflow.com/a/54569933/484190但为了方便起见,这里有一个例子:

import React, { FC } from "react";

interface CompProps {
  x?: number;
  y?: number;
}

const Comp: FC<CompProps> = ({ x = 10, y = 20 }) => {
  return <div>{x}, {y}</div>;
}

export default Comp;
Run Code Online (Sandbox Code Playgroud)

这将使 Typescript 知道您不必提供道具,并且它永远不会在您的组件中“未定义”


Mar*_*son 10

以下是有关状态函数的工作原理,以防其他人偶然发现这种情况.关键是将defaultProps声明为静态变量.

interface IBoxProps extends React.Props<IBoxProps> {
    x?: number;
    y?: number;
    height?: number;
    width?: number;
}

interface IBoxState {
    visible?: boolean;
}

export default class DrawBox extends React.Component<IBoxProps, IBoxState> {
    static defaultProps: IBoxProps;

    constructor(props: IBoxProps) {
        super(props);
    }
    ...
}

DrawBox.defaultProps = {
    x=0;
    y=0;
    height=10;
    weight=10;
};
Run Code Online (Sandbox Code Playgroud)

  • 这个答案与问题无关。它是类组件,而不是无状态功能组件。 (2认同)
  • 这对我有帮助,因为我使用的是 Class 组件。谢谢你。作为旁注,您可以像这样声明 `defaultProps`:`static defaultProps: Partial&lt;IBoxProps&gt;`,以防您不想为每个属性提供默认值。 (2认同)

rob*_*uck 5

对于React 16.7.0 起功能组件,'React.SFC' 类型被弃用,取而代之的是 ' '。React.FC

例子

type TFuncComp = React.FC<{ text: string }>

const FuncComp: TFuncComp = props => <strong>{props.text}</strong>

FuncComp.defaultProps = { text: 'Empty Text' }
Run Code Online (Sandbox Code Playgroud)

源代码中的弃用警告

FC(FunctionalComponent)输入源