最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What is the best way of defining optional propTypes in react? - Stack Overflow

programmeradmin2浏览0评论

I have an optional propType

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

If undefined, we will check for undefined before the function is called.

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

So, how do I handle the propType of type Function | undefined. Should I check for undefined before calling the function or define a default function () => {}

I have an optional propType

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

If undefined, we will check for undefined before the function is called.

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

So, how do I handle the propType of type Function | undefined. Should I check for undefined before calling the function or define a default function () => {}

Share Improve this question edited Feb 8, 2018 at 9:32 bhb asked Feb 8, 2018 at 9:26 bhbbhb 2,5614 gold badges21 silver badges32 bronze badges
Add a comment  | 

3 Answers 3

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

Then check if onSort exist.

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

OR

Define the propTypes like this:

static propTypes = {
  onSort: PropTypes.func
}

then have a default for onSort like so:

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

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.

发布评论

评论列表(0)

  1. 暂无评论