【问题标题】:React PropTypes do not work properly when defining propTypes with spread (...) operator使用 spread (...) 运算符定义 propTypes 时,React PropTypes 无法正常工作
【发布时间】:2017-10-12 08:47:29
【问题描述】:

我正在尝试使用单个 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 对象在调试器中看起来都是一样的,无论有没有展开。

我是不是做错了什么?

【问题讨论】:

    标签: reactjs react-proptypes


    【解决方案1】:

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

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

    【讨论】:

    • 嗨@Will Hawker,谢谢你的沙盒,它确实在那里工作。但就我而言,由于某种原因,这不起作用。看起来值得检查项目设置。
    • 看来我只是误解了 PropTypes 的概念。 transform-object-rest-spread 起到了神奇的作用。
    猜你喜欢
    • 2018-01-23
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    • 2016-07-04
    • 1970-01-01
    • 2017-06-08
    • 1970-01-01
    • 2016-09-25
    相关资源
    最近更新 更多