最近一直在看react。之前看react的时候很多都是旧的写法(es5),这几天因项目要求把es6和react一起结合看了一下,自己也写了几个demo,想把这些demo拿出来分享一下。虽然很简单,但对于初学react和es6的人来说我觉得还是有参考价值
class LikeButton extends React.Component { constructor(props) { super(props); //构造函数中初始化 this.state = { liked: false, color:"#f00" }; } //事件 handleClick(e) { var liked = this.state.liked; this.state.color = liked?'#f00':'#000'; var color = this.state.color; //事件中重置状态 this.setState({ liked: !this.state.liked, color:this.state.color }); } render() { const text = this.state.liked ? 'like' : 'haven\'t liked'; return ( <p style={{color:this.state.color}} onClick={this.handleClick.bind(this)}> You {text} this. Click to toggle. </p> ); } } ReactDOM.render( <LikeButton />, document.getElementById("example") )
这是效果图