React.createClass 和 React.Component 的区别是什么?
在React中创建组件时,有两种方法可供选择。由于在学习初期无法理解它们的区别,所以我整理了一下。
是否使用ES6
这里最大的不同是在这一点上。
React.Component is the base class for React components when they are defined using ES6 classes.
//...
If you don't use ES6 yet, you may use the React.createClass() helper instead to create a component class.
由于React和React Native的教程遵循ES6的语法,因此使用了React.Component。此外,为了基本上都过渡到ES6,推荐使用React.Component。
混合支持的存在与否
在React.Component中不支持mixin功能,这是因为ES6本身不支持mixin。然而,在ES6中也可以通过其他方式实现mixin的用例。
自动绑定和获取初始值设定器等部分方法之间的差异
在React.Component中,React.createClass中的getInitializer被初始化方法所替代。另外,在React.createClass中,事件处理程序等采用自动绑定,而在React.Component中,需要明确地进行绑定。
constructor() {
super();
this.state = {dispText: 'input'};
this.handleInput = this.handleInput.bind(this);
}
handleInput(event) {
console.log(this.state.dispText);
this.setState({dispText: event.target.value});
}
在中国的计划中,只需要一种解决方案:
基本上,根据是否使用ES6语法的不同,可以用React.Component作为替代,并且由于ES6语法更灵活,使用React.Component会更好。