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

javascript - Is it safe to pass undefined in React's onClick? - Stack Overflow

programmeradmin2浏览0评论

Is it safe to pass undefined in React's onClick handler?

I just tried and everything still works, but I can't find any line about that in docs.

Example:

function MonthBar(props) {
  /* is it okay when props.onClick === undefined ? */
  return <span onClick={props.onClick}>{props.monthName}</span>;
}

MonthBar.propType = {
  onClick:  React.PropTypes.func, // optional                   
  monthName: React.PropTypes.string.isRequired
};

Is it safe to pass undefined in React's onClick handler?

I just tried and everything still works, but I can't find any line about that in docs.

Example:

function MonthBar(props) {
  /* is it okay when props.onClick === undefined ? */
  return <span onClick={props.onClick}>{props.monthName}</span>;
}

MonthBar.propType = {
  onClick:  React.PropTypes.func, // optional                   
  monthName: React.PropTypes.string.isRequired
};
Share Improve this question asked Aug 28, 2016 at 17:44 Alex PovarAlex Povar 4,9603 gold badges32 silver badges44 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

It's perfectly valid to pass in undefined as the onClick handler. They already have to handle that case implicitly since it's an optional parameter.

passing undefined can be handled by checking it on your onClick,

function MonthBar(props) {
/* is it okay when props.onClick === undefined ? */
  return (
   <span onClick={props.onClick !== undefined? props.onClick : ''}>
    {props.monthName}
   </span>);
}

MonthBar.propType = {
  onClick:  React.PropTypes.func, // optional                   
  monthName: React.PropTypes.string.isRequired
}; 

the concern should be more about you want to pass the undefined to the onClick or not

发布评论

评论列表(0)

  1. 暂无评论