Raymond巍达

导航

 

使用es6语法与原本es5语法几个有区别的地方

1.React.creatClass与React.Component

1 var Component = React.createClass({  
2   render() {
3     return (
4       <div></div>
5     );
6   }
7 });
 1 class Component extends React.Component {  
 2   constructor(props) {
 3     super(props);
 4   }
 5   render() {
 6     return (
 7       <div></div>
 8     );
 9   }
10 }

 

2.propType和defaultProps

 1 var Component = React.createClass({  
 2   propTypes: {
 3     name: React.PropTypes.string
 4   },
 5   getDefaultProps() {
 6     return {
 7 
 8     };
 9   },
10   render() {
11     return (
12       <div></div>
13     );
14   }
15 });
 1 class Component extends React.Component {
 2 
 3   /* static propTypes = { // as static property
 4         title: React.PropTypes.string
 5 
 6         //需要babel转码
 7 
 8     };*/
 9 
10     constructor(props) {
11         super(props);
12     }
13 
14     render() {
15         return (
16             <h1>{this.props.title}</h1>
17         );
18     }
19 }
20 
21 //静态属性,注意这两个属性都是加到类本身的属性而不是类的实例的属性
22 Component.propTypes = {
23     title : React.PropTypes.string.isRequired  //被要求是字符串类型,其他类型报错
24 };
25 
26 Component.defaultProps  = {
27     title : 'hello world'
28 };

3.状态区别

 1 var Component = React.createClass({
 2     // return an object
 3     getInitialState(){ 
 4         return {
 5             isEditing: false
 6         }
 7     }
 8     render(){
 9         return <div></div>
10     }
11 })
 1 class Component extends React.Component{
 2     constructor(props){
 3         super(props);
 4         this.state = { // define this.state in constructor
 5             isEditing: false
 6         } 
 7     }
 8     render(){
 9         return <div></div>
10     }
11 }

4.this区别

 1 var Components = React.createClass({  
 2   handleClick() {
 3     console.log(this); // React Component instance
 4   },
 5   render() {
 6     return (
 7       <div onClick={this.handleClick}></div>//会切换到正确的this上下文
 8     );
 9   }
10 });
 1 class Components extends React.Component {  
 2   constructor(props) {
 3     super(props);
 4     this.handleClick = this.handleClick.bind(this);//需要手动处理一下this
 5   }
 6   handleClick() {
 7     console.log(this); // React Component instance
 8   }
 9   render() {
10     return (
11       <div onClick={this.handleClick}></div>
12     );
13   }
14 }

5.ReactDOM.findDOMNode

 1 class Component extends React.Component {
 2   componentDidMount() {
 3     let child = ReactDOM.findDOMNode(this.child);  //如果ref绑定在组件中则需要调用ReactDOM.findDOMNode()方法来拿取DOM节点
 4     let title = this.title;  //如果ref绑定在虚拟DOM中,则可以直接拿到DOM节点
 5   }
 6   render() {
 7     return(
 8       <div>
 9         <ChildComponent ref={(div) => {this.child = div;}} /> //官方文档中建议用回调函数的形式来写ref属性
10         <h1 ref={(h1) => {this.title = h1;}}>...</h1>
11       </div>
12     );
13   }
14 }

 

posted on 2016-11-25 15:37  Raymond巍达  阅读(1040)  评论(0编辑  收藏  举报