先看一段代码:一个简单的点赞自增组件;
import ReactDOM from 'react-dom';
import React, { Component } from 'react';
class Profile extends Component {
constructor( props ) {
super( props )
this.state = {
liked: 0
};
this.likedCallback = this.likedCallback.bind(this);
}
likedCallback(){
console.log("ooooo")
let liked = this.state.liked;
liked++;
this.setState({
liked
});
}
render(){
return (
<div>
<h1>我的名字叫 {this.props.name}</h1>
<h2>我今年{this.props.age}岁</h2>
<button onClick={this.likedCallback}>给我点赞</button>
<h2>点赞总数:{this.state.liked}</h2>
</div>
)
}
}
const props = {
name:"hahaha",
age:"12"
}
let root = document.getElementById('app');
ReactDOM.render(
<Profile {...props}/>, root
);
有点不太明白为什么要交这一句:this.likedCallback = this.likedCallback.bind(this);
当然还有一种写法是不加这一句,但是在这一句:<button onClick={this.likedCallback}>给我点赞</button>
要改成:<button onClick={this.likedCallback.bind(this)}>给我点赞</button>
自己先顶一下啊