javascript - react 使用ES6的写法,PropTypes为何不生效?
ringa_lee
ringa_lee 2017-04-11 10:48:32
[JavaScript讨论组]
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')
);
ringa_lee
ringa_lee

ringa_lee

全部回复(5)
怪我咯

类属性不是ES6的提案,需要babel支持

http://babeljs.io/docs/plugins/transform-class-properties/

大家讲道理

这是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"
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号