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

时间:2017-10-12 08:47:29

标签: reactjs react-proptypes

我试图让单个PropTypes定义在几个组件中重用它,并且遇到问题。我在单独的类中定义静态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>
    )
  }
}
&#13;
&#13;
&#13;

example-type.js就是:

&#13;
&#13;
import PropTypes from 'prop-types';

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

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

export default ExampleType;
&#13;
&#13;
&#13;

这样做,PropTypes检查不会发生。如果我将defaultProps定义更改为不带扩展运算符的定义:

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

比按预期的那样工作。

嗯,我知道重复使用单个属性类型定义可以通过不同的方式获得,例如https://stackoverflow.com/a/37720537/2335174,但我很好,为什么我的带扩展运算符的变体不起作用。在两种情况下,MyComponent.propTypes对象在调试器中看起来都是相同的,有和没有传播。

我做错了吗?

1 个答案:

答案 0 :(得分:1)

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

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