使用传播(...)运算符定义propTypes时,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>
    )
  }
}

example-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
  }

比预期的工作。

好吧,我知道可以以不同的方式重用单个属性类型定义,例如:https ://stackoverflow.com/a/37720537/2335174,但是我想知道为什么我的带有传播运算符的变体不起作用。在两种情况下,无论是否传播,MyComponent.propTypes对象在调试器中的外观都相同。

难道我做错了什么?

威尔·霍克

它似乎对我有用,请参见此处:https : //codesandbox.io/s/jlll2zm6xv

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章