【问题标题】:Optional function prop in React component Flow type check failReact 组件流类型检查中的可选功能道具失败
【发布时间】: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 &amp;&amp; this.props.exampleFn !== undefined) {...}

this.props.exampleFn &amp;&amp; this.props.exampleFn()
等知道我们正在防范可能为空/未定义的值,但我找不到任何有效的东西。当然,将 prop 类型更改为 React.PropTypes.func.isRequired 不会导致错误,但我想保持这个 prop 是可选的。

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

【问题讨论】:

  • if (this.props.exampleFn != null) 工作吗?

标签: javascript reactjs flowtype


【解决方案1】:

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

...

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

...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    • 2021-10-24
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多