我喜欢按以下方式编写默认道具:
interface IMyFunction {
p1?: string;
p2: string;
}
const MyFunction = (props: IMyFunction) => {
const defaultProps: Required<IMyFunction> = {
p1: "v1",
...props,
};
...
}
我知道MyFunction.defaultProps已被弃用,现在需要使用默认参数,所以我使用它们,但使用我的方法,我将它们合并到常量中,defaultProps
因为我发现它更方便。这种方法有什么我没有看到的问题吗,还是我应该以标准方式使用默认参数?
是的,在纯 JavaScript 函数中使用自定义是完全没问题的
defaultProps
,但由于缺乏静态类型,该方法与 TypeScript 相比略有不同。在纯 JavaScript 中,您可以通过在函数参数中结合使用解构和默认值来为 props 设置默认值,或者可以为
defaultProps
组件的属性分配默认值。