class LikeButton extends Component{
static defaultProps = {
likedText: 'XXXX',
unlikedText: '√√√√√√'
}
constructor(){
super();
this.state = {
isLiked : false
}
}
handleOnClick(){
console.log(this.state.isLiked);
this.setState({
isLiked : !this.state.isLiked
})
console.log(this.state.isLiked);
if(this.props.onClick){
this.props.onClick();
}
}
render(){
const wording = this.props.wording || {
liked:'取消',
unliked:'点赞'
}
return(
<div>
<button onClick={this.handleOnClick.bind(this)}>
{this.state.isLiked ? '赞' : '踩'} 👍
</button>
{/* 两种写法 */}
<button onClick={()=>{this.handleOnClick()}}>
{this.state.isLiked ? '赞' : '踩'} 👍
</button>
<button onClick={()=>{this.handleOnClick()}}>
{this.state.isLiked ? wording.liked : wording.unliked} 👍
</button>
<button onClick={()=>{this.handleOnClick()}}>
{this.state.isLiked ? this.props.likedText : this.props.unlikedText} 👍
</button>
</div>
)
}
}
ReactDOM.render(
<div>
<LikeButton onClick={()=>console.log('11')} />
{/*这些 on 的事件监听只能用在普通的 HTML 的标签上,而不能用在组件标签上。这里不会log出来11。要想出来得加上/********************这里的if判断*/}
<LikeButton wording={{liked:'已赞',unliked:'赞'}} />
{/* props可以包括字符串,对象,数字,数组甚至是函数。props 一旦传入,就不可以在组件内部对它进行修改。*/}
<LikeButton />
</div>,
document.getElementById('root')
);