【发布时间】:2015-02-18 02:11:33
【问题描述】:
我正在使用 React 的 PropTypes 和 Flow 类型检查器,但在获取可选函数 prop 以通过类型检查时遇到问题。这是一个例子:
var Example = React.createClass({
propTypes: {
exampleFn: React.PropTypes.func
},
handleClick: function() {
if (this.props.exampleFn) {
this.props.exampleFn();
}
},
render: function() {
return <a onClick={this.handleClick}>Click here</a>;
}
});
虽然我正在检查 this.props.exampleFn 不为空,但针对此代码运行 Flow 的类型检查器会给我错误
call of method exampleFn
Function cannot be called on possibly null or undefined value
我尝试了不同的变体,例如if (this.props.exampleFn !== null && this.props.exampleFn !== undefined) {...}
或this.props.exampleFn && this.props.exampleFn()
等知道我们正在防范可能为空/未定义的值,但我找不到任何有效的东西。当然,将 prop 类型更改为 React.PropTypes.func.isRequired 不会导致错误,但我想保持这个 prop 是可选的。
我怎样才能得到一个可选的函数道具来通过类型检查?
【问题讨论】:
-
if (this.props.exampleFn != null)工作吗?
标签: javascript reactjs flowtype