静态propTypes在ES6下不工作 [英] Static propTypes not working under ES6

查看:125
本文介绍了静态propTypes在ES6下不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为道具添加一些规则:

I want to add some rules for props:

import React, { Component } from 'react'

export default class App extends Component {
  static propTypes = { name: React.PropTypes.string.isRequired };

  render() {
    return(
    )
  }
}

但是我得到了一个错误:

But I got this an error:

Warning: Failed prop type: Required prop `name` was not specified in `App`.

我有这个配置为babel:

I have this configuration for babel:

{
  "presets": ["es2015", "react"],
  "plugins": ["transform-runtime", "transform-class-properties"]
}

我做错了什么?

更新更改代码:使用 static

推荐答案

您似乎没有透过代码来识别静态类属性。
如果您使用的是babel,可以通过使用类属性转换来启用: https://babeljs.io/docs/plugins/transform-class-properties/

It appears the you aren't transpiling your code in a way that can recognize static class properties. If you are using babel this can be enabled by using the Class Property Transform : https://babeljs.io/docs/plugins/transform-class-properties/.

在我们的代码库中,我们使用第1阶段预设功能, https://babeljs.io/docs/plugins/preset-stage-1/

In our code base we get this functionality with the Stage 1 preset, https://babeljs.io/docs/plugins/preset-stage-1/

当然可以总是在类上定义你的proptypes:

Of course you could always define your proptypes on the class:

export default class App extends Component {
  ...
  render() {
    ...
  } 
}

App.propTypes = {
 data: PropTypes.object.isRequired...
}

^^这不需要任何特殊的透明度。

^^ this doesn't require any special transpilation.

类静态属性很好,所以你可以像这样设置它

The in class static property is nice though so you can set it up like this

export default class App extends Component {
  static propTypes = { name: React.PropTypes.string.isRequired };
  render() {...} 
}

而不是定义在构造函数中的这个中的propTypes。

rather than define the propTypes on this in the constructor.

这篇关于静态propTypes在ES6下不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆