本文主要是介绍contextTypes was defined as an instance property on MyButton. Use a static property to define contex,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
问题描述
:在使用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
}
上面就是解决办法
这篇关于contextTypes was defined as an instance property on MyButton. Use a static property to define contex的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!