6

我正在使用 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不是 null,但针对此代码运行 Flow 的类型检查器会给我错误

call of method exampleFn
Function cannot be called on possibly null or undefined value

我尝试了不同的变体,例如
if (this.props.exampleFn !== null && this.props.exampleFn !== undefined) {...}
or
this.props.exampleFn && this.props.exampleFn()
等​​,以知道我们正在防范可能为 null/undefined 的值,但我找不到任何有效的方法。当然,将道具类型更改为React.PropTypes.func.isRequired不会出现错误,但我想保持这个道具是可选的。

我怎样才能获得一个可选的函数道具来通过类型检查?

4

1 回答 1

10

这是我们发现保持 PropType 可选但仍然通过 Flow 类型检查的一种方法。

...

handleClick: function() {
  var exampleFn = this.props.exampleFn || null;
  if (exampleFn) {
    exampleFn();
  }
},

...
于 2014-12-22T01:10:17.260 回答