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

Is it safe to pass undefined in React's onClick handler? I just tried and everything still works,

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742305662a4418889.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信