React with TypeScript - define defaultProps in stateless function

前端 未结 7 1617
梦如初夏
梦如初夏 2021-02-01 04:56

I\'m using React with TypeScript and I\'ve created stateless function. I\'ve removed useless code from the example for readability.

interface CenterBoxProps exte         


        
7条回答
  •  渐次进展
    2021-02-01 05:16

    I believe a better way than described in the React docs is simply to use Javascript / Typescript default arguments.

    There's an answer here: https://stackoverflow.com/a/54569933/484190 but for convenience, here's an example:

    import React, { FC } from "react";
    
    interface CompProps {
      x?: number;
      y?: number;
    }
    
    const Comp: FC = ({ x = 10, y = 20 }) => {
      return 
    {x}, {y}
    ; } 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

提交回复
热议问题