简体   繁体   English

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

[英]React with TypeScript - define defaultProps in stateless function

I'm using React with TypeScript and I've created stateless function.我正在将 React 与 TypeScript 一起使用,并且创建了无状态函数。 I've removed useless code from the example for readability.为了可读性,我从示例中删除了无用的代码。

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

Everything is great and this code is working correctly.一切都很好,这段代码工作正常。 But there's my question: how can I define defaultProps for CenterBox component?但我的问题是:如何为CenterBox组件定义defaultProps

As it is mentioned in react docs :正如反应文档中提到的那样:

(...) They are pure functional transforms of their input, with zero boilerplate. (...) 它们是输入的纯函数转换,零样板。 However, you may still specify .propTypes and .defaultProps by setting them as properties on the function, just as you would set them on an ES6 class.但是,您仍然可以通过将 .propTypes 和.defaultProps设置为函数的属性来指定它们,就像在 ES6 类上设置它们一样。 (...) (……)

it should be easy as:它应该很容易,因为:

CenterBox.defaultProps = {
    minHeight: 250
}

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

So again: how can I correctly define defaultProps in my above stack (React + TypeScript)?再说一遍:如何在上面的堆栈(React + TypeScript)中正确定义defaultProps

After 2 hours of looking for solution... it's working .经过 2 个小时的寻找解决方案......它正在工作

If you want to define defaultProps , your arrow function should look like:如果你想定义defaultProps ,你的箭头函数应该是这样的:

export const CenterBox: React.SFC<CenterBoxProps> = props => {
    (...)
};

Then you can define props like:然后你可以定义道具,如:

CenterBox.defaultProps = { someProp: true }

Note that React.SFC is alias for React.StatelessComponent .需要注意的是React.SFC是别名React.StatelessComponent

I hope that this question (and answer) help somebody.我希望这个问题(和答案)对某人有所帮助。 Make sure that you have installed newest React typings.确保你安装了最新的 React 类型。

I believe a better way than described in the React docs is simply to use Javascript / Typescript default arguments.我相信比 React 文档中描述的更好的方法是简单地使用 Javascript / Typescript 默认参数。

There's an answer here: https://stackoverflow.com/a/54569933/484190 but for convenience, here's an example:这里有一个答案: 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;

This will allow Typescript to know that you don't have to provide the prop, and also that it will never be "undefined" inside your component这将使 Typescript 知道您不必提供道具,并且它永远不会在您的组件中“未定义”

And here's how it works for stateful functions in case others stumble on this.这是它如何适用于有状态函数,以防其他人偶然发现。 The key is declaring defaultProps as a static variable.关键是将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;
};

For Functional Components as of React 16.7.0 the 'React.SFC' type is being deprecated in favour of ' React.FC '.对于React 16.7.0功能组件,'React.SFC' 类型被弃用,取而代之的是' React.FC '。

Example示例

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

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

FuncComp.defaultProps = { text: 'Empty Text' }

Deprecation Warning in Source 源代码中的弃用警告

FC (FunctionalComponent) Type in Source FC(FunctionalComponent)输入源

Typing default props in function component with React.FC can result in false type error:使用 React.FC 在函数组件中输入默认 props 可能会导致错误类型错误:

   type Props = {
     required: string,
   } & typeof defaultProps;

   const defaultProps = {
     optDefault: 'optDefault'
   };

   const MyComponent: React.FC<Props> = (props: Props) => (
     <ul>
       <li>required: {props.required}</li>
       <li>optDefault: {props.optDefault}</li>
     </ul>
   )
   MyComponent.defaultProps = defaultProps;


   ReactDOM.render(
     <div>
       <MyComponent
         required='required'
         optDefault='over written'
       />
       <MyComponent   /* type error  <---- false type error */
         required='required'
       />
     </div>,
     document.getElementById('app')
   );

error:错误:

[tsserver 2741] Property 'optDefault' is missing in type '{ required: string; }' but required in type '{ optDefault: string; }'. [E]

Another solution proposed is to use Javascript's own default function parameters:提出的另一个解决方案是使用 Javascript 自己的默认函数参数:

type Props = {
  required: string,
  optDefault?: string
}

const MyComponent:  React.FC<Props> = ({
  required,
  optDefault='default'
}: Props) => (
  <ul>
    <li>required: {required}</li>
    <li>optDefault: {optDefault}</li>
  </ul>
)

ReactDOM.render(
  <div>
    <MyComponent
      required='required'
      optDefault='over written'
    />
    <MyComponent
      required='required'
    />
  </div>,
  document.getElementById('app')
);

But the problem with this solution is that if you forgot to provide default, a run time bug will result:但是这个解决方案的问题是,如果你忘记提供默认值,就会导致一个运行时错误:

const MyComponent: React.FC<Props> = ({
  required,
  optDefault //='optDefault' //<--- if you forgot to provide default
}: Props) => (
  <ul>
    <li>required: {required}</li>
    <li>optDefault: {optDefault}</li> {/* <-- result in bug */}
  </ul>
)

A better solution is not using React.FC at all, simply rely on Typescript type inference:更好的解决方案是根本不使用 React.FC,只需依赖 Typescript 类型推断:

type Props = {
  required: string,
} & typeof defaultProps;

const defaultProps = {
  optDefault: 'optDefault'
};

const MyComponent = (props: Props) => (
  <ul>
    <li>required: {props.required}</li>
    <li>optDefault: {props.optDefault}</li>
  </ul>
)
MyComponent.defaultProps = defaultProps


ReactDOM.render(
  <div>
    <MyComponent
      required='required'
      optDefault='over written'
    />
    <MyComponent
      required='required'
    />
  </div>,
  document.getElementById('app')
);

你可以把它放在你的组件中

static defaultProps: any;

Simplest for me is to define (partial) defaults in the defaultProps directly:对我来说最简单的是直接在 defaultProps 中定义(部分)默认值:

export default class TSError extends React.Component<ITSErrorProps, {}> {
  private static defaultProps: Partial<ITSErrorProps> = {
    fullPage: true,
    controlClick: true,
    doubleClick: true
  };

...

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM