contextTypes was defined as an instance property on MyButton. Use a static property to define contex

contextTypes was defined as an instance property on MyButton. Use a static property to define contex

标签: class es6
1018人阅读  评论(0)  收藏  举报
  分类:
JavaScript(31)   es6(7)   前端问题总结

问题描述
:在使用es6语法时,定义一个类方法时,出现如下的问题:

contextTypes was defined as an instance property on MyButton. Use a static property to define contextTypes instead.
  • 1

出现上面问题的原因是,在es6版本中,对一些语法进行了更改,更改的内容中都有以下属性的修改: 
将propTypes、getDefaultTypes等类属性移到类外面定义,由于ES6类中只允许定义方法并不允许定义类属性,所以像原先会在 createClass 中定义的 propTypes 、 getDefaultTypes 、 displayName 还有 contextTypes 等组件属性都要放到类外面来赋值。 
也就是具体如下实现: 
原来的方式:

var MyComponent = React.createClass({  
    displayName:'MyComponent',
    propTypes: {
        prop1: React.PropTypes.string
    },
    getDefaultProps: function() {
        return { prop1: '' };
    }
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

ES6的方式:

class MyComponent extends React.Component {...}  
MyComponent.displayName = 'MyComponent';  
MyComponent.propTypes = {  
    prop1: React.PropTypes.string
}
MyComponent.defaultProps = {  
    return { prop1: '' };
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

解决方案
:将使用的 
contextTypes属性放置到class类的外边,然后重新编译调用即可,然后使用组件名进行调用,形式如下面代码所示:

class MyButton extends React.Component{
    constructor(props,context)
    {
        super(props,context);
        this.handleSubmit=this.handleSubmit.bind(this);
    }
    // contextTypes: {
    //     router: React.PropTypes.object
    // }
    //...上面的contextTypes等属性的形式是错的,由于ES6类中只允许定义方法并不允许定义类属性
}
MyButton.contextTypes= {
    router: React.PropTypes.object
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

上面就是解决办法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值