React 創建組件的 3種方式 原

無狀態和函數式(stateless)

寫法一

const Hello = (props) => (
    <div> Hello {props.title} {props.name} </div>
)

寫法二

function HelloComponent(props, /* context */) {
  return (
     <div>Hello {props.name}</div>
    )
}
ReactDOM.render(<HelloComponent name="Sebastian" />, mountNode) 

ES5 React.createClass

var CommentBox = React.createClass({  
  getInitialState: function() {
    return {data: []};
  },
  componentDidMount: function() {
  },
  render: function() {
    return (
      <div className="">
      </div>
    );
  }
});

ES6 React.component

import React, {Component} from 'react'
export class App extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div>
        //TODO
      </div>
    );
  }
}

 

注意:

React.component 創建的組件,其成員函數不會自動綁定 this

class Contacts extends Component {  
  constructor(props) {
    super(props);
  }
  handleClick() {
    console.log(this); // null
  }
  render() {
    return (
      <div onClick={this.handleClick}></div>
    );
  }

其綁定 this 通常有3種方法

constructor(props) {
  super(props);
  this.handleClick = this.handleClick.bind(this); //構造函數中綁定
}


<div onClick={this.handleClick.bind(this)}></div> //使用bind來綁定

<div onClick={()=>this.handleClick()}></div> //使用arrow function來綁定,自動捕捉其所在上下文

1、只要有可能,儘量使用無狀態組件創建形式。

2、否則(如需要state、生命週期方法等),使用`React.Component`這種es6形式創建組件

3. 使用原生事件綁定,在組件銷燬時需要手動移除監聽

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章