react的es6,props获取的问题?

react的props的es6写法问题

//1.为毛要super??还要bind?不能直接this.props么?
class Count extends React.Component{
    constructor(props){
        super(props);  //为毛要super??
        this.oddChange=this.oddChange.bind(this);
    }
render(){
        const {value,add,sub}=this.props  //2.为什么是这样子的写法?然后就不用super了?
        return (
            <div>
                <span>{value}</span>

有点乱,希望大神解释下

阅读 3.9k
3 个回答

class constructor super
都是es6中的写法。
class 创建一个类,constructor是构造器,在构造函数new的时候执行,其中的super其实就是父类,调用。

super() 相当于 Component.call(this)

这其实就是继承的问题了。在子类的构造函数执行父类,继承一些私有的属性.
对比es5的creatClass的写法,就是有了es6的class写法不需要 react封装的creatClass也可以实现很好的 原型,私有属性的继承。
这就是为什么你能直接this.props 可以取到传进来的属性props。因为在构造函数实例化的时候都被 挂载到实例上了。
同样的定义state也从一个钩子函数getInitialState 变成了直接写 this.state ={} 定义。

关于bind(this) 的问题。
如果是定义在React.Component 的原型上的函数,比如componentWillMount DidMount render ......
里面的this当然就是实例了。方便拿state 和props
但是其他函数,比如一个handler,你直接定义的话,定义到私有属性上。调用是this.handler
有时候一个

<div onClick = {this.handler} ></div>

因为事件绑定的关系,这里handler的this 就变成了这个div。所以 实例化就要绑定this为当前组件实例了。

MDN上的注释: Note: In derived classes, super() must be called before you can use 'this'. Leaving this out will cause a reference error.

class Square extends Polygon {
  constructor(length) {
    // Here, it calls the parent class' constructor with lengths
    // provided for the Polygon's width and height
    super(length, length);
    // Note: In derived classes, super() must be called before you
    // can use 'this'. Leaving this out will cause a reference error.
    this.name = 'Square';
  }

  get area() {
    return this.height * this.width;
  }

  set area(value) {
    this.area = value;
  } 
}

链接: https://developer.mozilla.org...

  1. 首先理解super的作用是什么

  2. 理解ES6的class中this的特点

理解了这两个你就明白为什么这么写了。

也可以去仔细看下我的个人系列文章《React从入门到精通系列》

https://segmentfault.com/u/zh...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题