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>
有点乱,希望大神解释下
class constructor super
都是es6中的写法。
class 创建一个类,constructor是构造器,在构造函数new的时候执行,其中的super其实就是父类,调用。
这其实就是继承的问题了。在子类的构造函数执行父类,继承一些私有的属性.
对比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
有时候一个
因为事件绑定的关系,这里handler的this 就变成了这个div。所以 实例化就要绑定this为当前组件实例了。