一 模塊
1 引入模塊以便使用
用import實現:
import '模塊文件地址' import 組件 from '模塊文件地址'
2 導出模塊
用export default實現:
export default class MyComponent extends Component{
...
}
引用:
import MyComponent from './MyComponent';
二 組件
1 定義組件
通過定義一個繼承自React.Component的class來定義一個組件類:
class Photo extends React.Component {
render() {
...
}
}
2 定義組件方法
直接用名字(){},很像Java定義類方法的寫法:
class Photo extends React.Component {
componentWillMount() {
}
render() {
return (
<Image source={this.props.source} />
);
}
}
3 定義組件的屬性類型和默認屬性
統一使用static成員來實現:
class Video extends React.Component {
static defaultProps = {
autoPlay: false,
maxLoops: 10,
}; // 注意這里有分號
static propTypes = {
autoPlay: React.PropTypes.bool.isRequired,
maxLoops: React.PropTypes.number.isRequired,
posterFrameSrc: React.PropTypes.string.isRequired,
videoSrc: React.PropTypes.string.isRequired,
}; // 注意這里有分號
render() {
return (
<View />
);
} // 注意這里既沒有分號也沒有逗號
}
注意: 對React而言,static成員在IE10及之前版本不能被繼承,而在IE11和其它瀏覽器上可以,有時會帶來一些問題。React Native則不用擔心這個問題。
4 初始化STATE
在構造函數中初始化(這樣可以根據需要做一些計算):
class Video extends React.Component {
constructor(props){
super(props);
this.state = {
loopsRemaining: this.props.maxLoops,
};
}
}
5 把方法作為回調提供并使用
ES5下可以這么做:
//ES5
var PostInfo = React.createClass({
handleOptionsButtonClick: function(e) {
// Here, 'this' refers to the component instance.
this.setState({showOptionsModal: true});
},
render: function(){
return (
<TouchableHighlight onPress={this.handleOptionsButtonClick}>
<Text>{this.props.label}</Text>
</TouchableHighlight>
)
},
});
在ES5下,React.createClass會把所有的方法都bind一遍,這樣可以提交到任意的地方作為回調函數,而this不會變化。但官方現在認為這是不標準、不易理解的。
ES6下,需要通過bind來綁定this引用,或者使用箭頭函數(它會綁定當前scope的this引用)來調用:
//ES6
class PostInfo extends React.Component
{
handleOptionsButtonClick(e){
this.setState({showOptionsModal: true});
}
render(){
return (
<TouchableHighlight
onPress={this.handleOptionsButtonClick.bind(this)}
onPress={e=>this.handleOptionsButtonClick(e)}
>
<Text>{this.props.label}</Text>
</TouchableHighlight>
)
},
}
箭頭函數是在這里定義了一個臨時的函數,箭頭函數的箭頭=>之前是一個空括號、單個的參數名、或用括號括起的多個參數名,而箭頭之后可以是一個表達式(作為函數的返回值),或者是用花括號括起的函數體(需要自行通過return來返回值,否則返回的是undefined)。
即:箭頭函數箭頭前是參數,箭頭后是函數體或返回值。
注意:
不論是bind還是箭頭函數,每次被執行都返回的是一個新的函數引用,因此如果你還需要函數的引用去做一些別的事情(譬如卸載監聽器),那么必須自己保存這個引用:
// 錯誤的做法
class PauseMenu extends React.Component{
componentWillMount(){
AppStateIOS.addEventListener('change', this.onAppPaused.bind(this));
}
componentDidUnmount(){
AppStateIOS.removeEventListener('change', this.onAppPaused.bind(this));
}
onAppPaused(event){
}
}
// 正確的做法
class PauseMenu extends React.Component{
constructor(props){
super(props);
this._onAppPaused = this.onAppPaused.bind(this);//注意這里
}
componentWillMount(){
AppStateIOS.addEventListener('change', this._onAppPaused); //還有這里
}
componentDidUnmount(){
AppStateIOS.removeEventListener('change', this._onAppPaused);
}
onAppPaused(event){
}
}
三 Mixins
ES5下,經常使用mixin來為類添加一些新的方法,如PureRenderMixin:
var PureRenderMixin = require('react-addons-pure-render-mixin');
React.createClass({
mixins: [PureRenderMixin],
render: function() {
return <div className={this.props.className}>foo</div>;
}
});
但React官方已經不再打算在ES6里繼續推行Mixin,官方推薦,對于庫編寫者而言,應盡快放棄Mixin的編寫方式,推薦一種新的編碼方式:
//Enhance.js
import { Component } from "React";
export var Enhance = ComposedComponent => class extends Component {
constructor() {
this.state = { data: null };
}
componentDidMount() {
this.setState({ data: 'Hello' });
}
render() {
return <ComposedComponent {...this.props} data={this.state.data} />;
}
};
//HigherOrderComponent.js
import { Enhance } from "./Enhance";
class MyComponent {
render() {
if (!this.data) return <div>Waiting...</div>;
return <div>{this.data}</div>;
}
}
export default Enhance(MyComponent); // Enhanced component
用一個“增強函數”,來為某個類增加一些方法,并且返回一個新類,這無疑能實現mixin所實現的大部分需求。
四 解構與屬性延展
結合使用ES6+的解構和屬性延展,在給子組件傳遞一批屬性更為方便了。下面的例子把className以外的所有屬性傳遞給div標簽:
class AutoloadingPostsGrid extends React.Component {
render() {
var {
className,
...others, // contains all properties of this.props except for className
} = this.props;
return (
<div className={className}>
<PostsGrid {...others} />
<button onClick={this.handleLoadMoreClick}>Load more</button>
</div>
);
}
}
下面這種寫法,則是傳遞所有屬性的同時,用新的className值進行覆蓋({…this.props}寫在前邊):
<div {...this.props} className="override">
…
</div>
這個例子則相反,如果屬性中沒有包含className,則提供默認的值,而如果屬性中已經包含了,則使用屬性中的值({…this.props}寫在后邊)
<div className="base" {...this.props}>
…
</div>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。