react知识(一)React.createClassVsReact.Component

xiaoxiao2021-02-28  81

如果是通过看react视频学习的同仁们会发现,有的视频是通过React.createClass来讲解sample 有的视频是用React.component来开发sample,那俩者之间有啥差别呢。 前面讲解的主要是环境搭建方面的,现在我们开始关注下React组件本身: createClass是React以前版本的写法,现在Facebook官方逐渐废弃,所以尽量使用React.component来定义:

我们现在看下createClass的一个典型写法的例子:

import React,{Component} from 'react'; var ClickCount = React.createClass({ //初始化state getInitState: function () { return {count: 0} }, //点击事件 将state里的count进行累加 _handleClick: function () { this.setState(this.state.count + 1); }, render: function () { return ( <div> <h1>计数器:{this.state.count}</h1> <button onClick={this._handleClick}>点击计数</button> </div> ) } }); export default ClickCount;

如果改成ES6的写法: 差别一:ES6 Class 语法比起传统的对象字面量更为简洁。对于方法的定义不需要再使用 function 关键字,也不需要 , 来分开多个方法。 before

var ClickCount = React.createClass({ render: function () { return ...; } })

after

var ClickCount extends React.component{ render(){ return ...; } }

差别二:将初始 state 定义移动到构造函数中 before:

var ClickCount = React.createClass({ //初始化state getInitState: function () { return {count: 0} }, ... })

after:

var ClickCount extends React.component{ constructor(prop){ super(prop); this.state={count:0}; } }

差别三:绑定实例方法和回调到实例上 比如前面例子中的 _handleClick 方法里的 this 将会指向当前这个组件实例。当使用 ES6 Class 语法的时候,我们必须要手动为这些方法绑定执行上下文 before:

var ClickCount = React.createClass({ //初始化state ... //点击事件 将state里的count进行累加 _handleClick: function () { console.log(this); console.log(this.state); this.setState(this.state.count + 1); }, render: function () { return ( <div> <h1>计数器:{this.state.count}</h1> <button onClick={this._handleClick}>点击计数</button> </div> ) } }

点击按钮的时候会调用_handleClick方法,而且输出this与this.state都是可以的。我们来看下es6:

class ClickCounter extends Component{ constructor(prop){ super(prop); //先将这句话屏蔽掉 //this._handleClick=this._handleClick.bind(this); this.state={count:0}; } _handleClick(){ //输出null console.log(this); //报错误 state of null console.log(this.state) this.setState({count:this.state.count+1}); } render(){ return ( <div> <button onClick={this._handleClick}>click Me</button> <h1>click Count{this.state.count}</h1> </div> ) } }

所以es6的写法需要在constructor【构造】函数里面,进行手动绑定this对象

this._handleClick=this._handleClick.bind(this);

如果存在多个事件需要绑定时,操作是比较繁琐的: before:

class ExampleComponent extends React.Component { constructor() { super(); this._handleClick = this._handleClick.bind(this); this._handleFoo = this._handleFoo.bind(this); } // ... }

after:

class ExampleComponent extends React.Commponent{ _bind(...methods){ methods.forEach((method)=>this[method]=this[method].bind(this)); } constructor(){ this._bind('_handleClick', '_handleFoo'); } }
转载请注明原文地址: https://www.6miu.com/read-63245.html

最新回复(0)