当前位置: 移动技术网 > IT编程>开发语言>JavaScript > ES6下React组件的写法示例代码

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

2018年05月07日  | 移动技术网IT编程  | 我要评论
本文主要跟大家分享了es6下react组件的写法示例,下面来一起看看详细的介绍: 一:定义react组件 class hello extends react.c

本文主要跟大家分享了es6下react组件的写法示例,下面来一起看看详细的介绍:

一:定义react组件

class hello extends react.component {
 render() {
  return <h1>hello, {this.props.value}</h1>;
 }
}

二:声明prop类型与默认prop

class hello extends react.component {
 // ...
}
hello.proptypes = {
 value: react.proptypes.string
};
hello.defaultprops = {
 value: 'world'
};

三、设置初始state

class hello extends react.component {
 constructor(props) {
  super(props);
  this.state = {count: props.initialcount};
 }
 // ...
}

四、自动绑定

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>
  );
 }
}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网