contextTypes was defined as an instance property on MyButton. Use a static property to define contex
![](https://i-blog.csdnimg.cn/blog_migrate/65b365c30c3ce25eab2619e9e56b40ba.jpeg)
JavaScript(31)
es6(7)
前端问题总结
![](https://i-blog.csdnimg.cn/blog_migrate/25dbc88b55d4ea78727c33c97af433a3.jpeg)
![](https://i-blog.csdnimg.cn/blog_migrate/25dbc88b55d4ea78727c33c97af433a3.jpeg)
版权声明:本文为博主原创文章,若需转载,请注明出处:http://blog.csdn.net/suwu150 http://blog.csdn.net/suwu150/article/details/55520674
问题描述
:在使用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
上面就是解决办法