使用扩展 (...) 运算符定义 propTypes 时,React PropTypes 无法正常工作

React PropTypes do not work properly when defining propTypes with spread (...) operator

我正在尝试使用单个 PropTypes 定义以在多个组件中重用它,但遇到了问题。我在单独的 class 中定义静态 propTypes,然后将其作为模块导入。说,我有一个视图的 React 组件:

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ExampleType from './example-type.js';

class MyComponent extends Component {
  static propTypes = {
    ...ExampleType.propTypes,  // <--- note here, that's how I'm trying to make it work
    
    // and the line below duplicates same field from ExampleType.propTypes, 
    // this is needed because otherwise Linter throws an error
    // that PropTypes is defined, but never used:
    instanceName: PropTypes.string
  }
  
  static defaultProps = {
    ...ExampleType.defaultProps
  }
  
  render() {
    return (
      <div>
        <h3>{this.props.instanceName}</h3>
        <p>
          {this.props.instanceValue}
        </p>
      </div>
    )
  }
}

示例-type.js 是:

import PropTypes from 'prop-types';

class ExampleType {
  static propTypes = {
    instanceName: PropTypes.string,
    instanceValue: PropTypes.string
  }

  static defaultProps = {
    instanceName: '',
    instanceValue: ''
  }
}

export default ExampleType;

这样一来,PropTypes 检查就不会发生了。如果我将 defaultProps 定义更改为没有扩展运算符的定义:

  static propTypes = {
    // ...ExampleType.propTypes,     // and now without spread ...
    instanceName: PropTypes.string,
    instanceValue: PropTypes.string
  }

比预期的要好。

好吧,我知道可以通过不同的方式重用单个 属性 类型定义,就像这里 一样,但我很好奇为什么我的带有扩展运算符的变体不起作用。 MyComponent.propTypes 在两种情况下,对象在调试器中看起来都一样,有和没有传播。

我是不是做错了什么?

它似乎对我有用,请看这里:https://codesandbox.io/s/jlll2zm6xv

您是否在 Babel 设置中包含了 transform-object-rest-spread 插件?