简体   繁体   English

在反应中定义可选propTypes的最佳方法是什么?

[英]What is the best way of defining optional propTypes in react?

I have an optional propType 我有一个可选的propType

static defaultProps = {
   onSort: undefined, // undefined | () => {}
}

If undefined, we will check for undefined before the function is called. 如果未定义,我们将在调用函数之前检查undefined

_handleSort = () => {
   this.props.onSort && this.props.onSort()
}

So, how do I handle the propType of type Function | undefined 那么,我该如何处理Function | undefined类型的propType Function | undefined . Function | undefined Should I check for undefined before calling the function or define a default function () => {} 我应该在调用函数之前检查undefined还是定义默认函数() => {}

static propTypes = {
  onSort: PropTypes.oneOfType([
    PropTypes.func,
    PropTypes.any
  ])
}

Then check if onSort exist. 然后检查onSort存在。

if (this.props.onSort) {
  //do something
}

OR 要么

Define the propTypes like this: 像这样定义propTypes

static propTypes = {
  onSort: PropTypes.func
}

then have a default for onSort like so: 然后有onSort的默认值, onSort所示:

static defaultProps = {
   onSort: () => null
}

This issue suggests defining a default function as you have indicated above: https://github.com/yannickcr/eslint-plugin-react/issues/1067 这个问题建议定义一个默认函数,如上所示: https//github.com/yannickcr/eslint-plugin-react/issues/1067

Cmp.defaultProps = {
    onChange: () => {}
}

However, I am still trying to get this to work. 但是,我仍然试图让它发挥作用。 I'd be interested if you have any luck. 如果你有运气我会感兴趣的。

static defaultProps = {
  onSort: PropTypes.func,
}
if(this.props.onSort){
  //do something
}

What about this? 那这个呢? So you're right with checking the property before calling/using it. 所以在调用/使用它之前检查属性是正确的。

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

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