Typescript 将空函数反应为 defaultProps

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47438546/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:03:36  来源:igfitidea点击:

Typescript React empty function as defaultProps

reactjstypescripttypescript-typingstypescript2.0

提问by Fabrice

I have a Stateless Functional Component with an optional function parameter as property (onClick), I tried to define an empty function as default property to be able to do safely in my component :

我有一个带有可选函数参数作为属性 (onClick) 的无状态功能组件,我尝试将一个空函数定义为默认属性,以便能够在我的组件中安全执行:

 <span onClick={props.onClick} />

But I have the following error : 'Expression expected.'

但我有以下错误:“预期表达。”

interface IProps {
  size?: sizeType;
  onClick?: (e:any) => void;
}
const Foo: React.SFC = (props: IProps) => {
  // ...
};
const defaultProps: IProps = {
   size: 'default',
   onClick: () => void <-- Expression expected.
};
Foo = defaultProps;

How can I should do this?

我该怎么做?

回答by Daniel Derevjanik

You cannot use voidin javascript as return value. Instead of void, use nullas return value.

您不能void在 javascript 中使用作为返回值。代替void,null用作返回值。

onClick: () => null

回答by Remo H. Jansen

You can use the following:

您可以使用以下内容:

const defaultProps: IProps = {
   size: 'default',
   onClick: () => void(0)
};

回答by Scott Stern

I think using lodashes noop might be a good option because depending on the number of re-renders the component will have BEFORE the component has access to the prop, it will create that many references to an anonymous function that essentially is a place holder for the function you need. Something like:

我认为使用 lodashes noop 可能是一个不错的选择,因为根据组件在组件访问 prop 之前的重新渲染次数,它将创建对匿名函数的许多引用,该函数本质上是一个占位符你需要的功能。就像是:

import noop from 'lodash/noop';
MyComponent.defaultProps = {
  myfunc: noop,
};

Its a small optimization but also prevents the developer from creating an anonymous function for every default prop declaration that a func is needed in.

它是一个小的优化,但也阻止了开发人员为每个需要 func 的默认 prop 声明创建匿名函数。

回答by 1252748

I usually do

我通常做

MyComponent.defaultProps = {
  someNoop: f => f
}

as something that is short, easy to type, and will just return undefined.

作为简短、易于输入且只会返回的内容undefined