1. 程式人生 > 其它 >React建立元件的三種方式

React建立元件的三種方式

1.函式建立的元件,這種元件被稱為無狀態元件:具有以下主要特點

a: 元件不會被例項化,整體渲染效能得到提升

b: 元件不能訪問this物件

c: 元件無法訪問生命週期的方法

d: 無狀態元件只能訪問輸入的props,同樣的props會得到同樣的渲染結果,不會有副作用

如: function Upfile(props){

 return  <h1>{ props.title }<h1>}

ReactDOM.render(<Upfile name="檔名字" />,目標元素)

 

2.採用`React.createClass Es5寫法: 形式

var Upfile = React.createClass({

propTypes: {//定義傳入props中的屬性各種型別 initialValue: React.PropTypes.string },

 

 

defaultProps: {

//元件預設的props物件

initialValue: '' },

 

 

// 設定 initial state

getInitialState: function() {

//元件相關的狀態物件

return { text: this.props.initialValue || 'placeholder' };

},

3.React.Component是 Es6形式

class InputControlES6 extends React.Component {

 

 

constructor(props) { super(props);

 

 

// 設定 initial state this.state = { text: props.initialValue || 'placeholder' };

 

// ES6 類中函式必須手動繫結

this.handleChange = this.handleChange.bind(this);

}

總結: 2 3 方法相同,不同Es環境下的寫法,可以訪問this,周期函式