源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

ES6下React组件的写法示例代码

  • 时间:2020-04-18 22:29 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:ES6下React组件的写法示例代码
本文主要跟大家分享了ES6下React组件的写法示例,下面来一起看看详细的介绍: [b]一:定义React组件[/b]
class Hello extends React.Component {
 render() {
  return <h1>Hello, {this.props.value}</h1>;
 }
}
[b]二:声明prop类型与默认prop[/b]
class Hello extends React.Component {
 // ...
}
Hello.propTypes = {
 value: React.PropTypes.string
};
Hello.defaultProps = {
 value: 'world'
};
[b]三、设置初始state[/b]
class Hello extends React.Component {
 constructor(props) {
  super(props);
  this.state = {count: props.initialCount};
 }
 // ...
}
[b]四、自动绑定[/b]
class SayHello extends React.Component {
 constructor(props) {
  super(props);
  this.state = {message: 'Hello!'};
  // 这行很重要
  this.handleClick = this.handleClick.bind(this);
 }
 handleClick() {
  alert(this.state.message);
 }
 render() {
  // Because `this.handleClick` is bound, we can use it as an event handler.
  return (
   <button onClick={this.handleClick}>
    Say hello
   </button>
  );
 }
}
[b]总结[/b] 以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对编程素材网的支持。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部