问题描述
:在使用es6语法时,定义一个类方法时,出现如下的问题:contextTypes was defined as an instance property on MyButton. Use a static property to define contextTypes instead.
出现上面问题的原因是,在es6版本中,对一些语法进行了更改,更改的内容中都有以下属性的修改:
将propTypes、getDefaultTypes等类属性移到类外面定义,由于ES6类中只允许定义方法并不允许定义类属性,所以像原先会在 createClass 中定义的 propTypes 、 getDefaultTypes 、 displayName 还有 contextTypes 等组件属性都要放到类外面来赋值。
也就是具体如下实现:
原来的方式:
var MyComponent = React.createClass({
displayName:'MyComponent',
propTypes: {
prop1: React.PropTypes.string
},
getDefaultProps: function() {
return { prop1: '' };
}
});
ES6的方式:
class MyComponent extends React.Component {...}
MyComponent.displayName = 'MyComponent';
MyComponent.propTypes = {
prop1: React.PropTypes.string
}
MyComponent.defaultProps = {
return { prop1: '' };
}
解决方案
:将使用的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
}
上面就是解决办法