import React from 'react';
import ReactDOM from 'react-dom';
// Hello 通过extends继承了React所有属性和方法
class Hello extends React.Component{
// constructor用来创建和初始化Hello 的方法 构造函数
constructor (props) {
//super 在这里表示父类的(constructor)的构造函数,
//用来新建this对象,(目前感觉有点鸡肋,为什么不能直接使用this
//有点代加工的意思,(没有super)不代加工,就会报错)
super (props)
this.state = {
liked:''
}
console.log(this)
this.handleClick = this.handleClick.bind(this);
};
handleClick (event) {
console.log(this)
this.setState ({
liked:'这又是一段对话'
})
};
render () {
var text = this.state.liked;
return (
<div>
<p>这是一段对话</p>
<p>{text}</p>
<button type="button" onClick={this.handleClick}>按钮</button>
</div>
)
}
};
ReactDOM.render(
<Hello />,
document.getElementById('root')
)
使用React框架写的一个案例:
constructor方法中使用了,es6的指向
this.handleClick = this.handleClick.bind(this);
效果图:
打印的log:
Hello 使用 extends 继承React的属性和方法