react 使用ES6的写法,PropTypes为何不生效?

import React from 'react';
import ReactDOM from 'react-dom';

let data = 123;

class MyTitle extends React.Component {

    //static propTypes = {
    //    title: React.PropTypes.string.isRequired
    //};//用这种方式则报错

    render() {
        return <h1> {this.props.title} </h1>;
    }
}

MyTitle.propTypes = {
    title: React.PropTypes.string.isRequired
};//验证不生效

ReactDOM.render(
    <MyTitle title={data}/>,
    document.getElementById('example')
);
阅读 10.8k
6 个回答

15.5.0版本之后,废除这个属性,需要单独引入prop-types这个包。
在组件中引入import PropTypes from 'prop-types'
在组件中使用:
ComponentChild.propTypes = {
name: PropTypes.string
}

这是es7的写法,需要在babel设置的query里面加上stage-0

npm install babel-preset-stage-0 -D

{
    test: /\.(js|jsx)$/,
    loader: 'babel',
    query: {
        presets: ['es2015', 'react', 'stage-0']
    }
}
    //static propTypes = {
    //    title: React.PropTypes.string.isRequired
    //};//用这种方式则报错
  1. static method 而不是 static property

  2. = 语法不对

我也是这样的情况,错误提示缺少类关键转换,不知道错在那一步。

新手上路,请多包涵

ES6 class语法创建组件,其内部只允许定义方法,而不能定义属性,class的属性只能定义在class之外。所以propTypes要写在组件外部,getDefaultProps也要写在外部。

class MyTitle extends React.Component {
    render() {
        return <h1> {this.props.title} </h1>;
    }
}

MyTitle.propTypes = {
    title: React.PropTypes.string.isRequired
};

Mytitle.defaultProps = {
        title : "this is default title"
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题