一 模塊
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){
}
}