React Native ES6寫法總結
1、每個介面,我們需要引入一些我們依賴的模組,比如“react”,“react-native”等等。使用的關鍵字就是import,基本寫法如下:
import React,{ Component } from 'react';
import { View,Text,StyleSheet } from 'react-native';
2、元件化是react/react-native的核心,如何寫一個元件呢?react/react-native是通過類的方式進行的,一個元件的基本書寫方式是這樣的 :
class Home extends Component {
render() {
return (
<View>
<Text>我是Component</Text>
</View>
)
}
}
3、當你寫好了一個元件,你的元件需要丟擲去給別的元件使用,在react/react-native中的引入方式就是export關鍵字:
export default class Home extends Component {
render() {
return (
<View>
<Text>我是ThirdPageComponent</Text>
</View>
)
}
}
4、寫好了一個元件,我們這個元件的樣式總要控制吧?這時候需要用到StyleSheet關鍵字,它有一個create()方法,接受一個物件作為引數。從而實現了樣式的寫法。
程式碼片段類似這樣:
const styles = StyleSheet.create({
container:{
backgroundColor: "#CCCCCC",
flex:1,
justifyContent: "center",
alignItems: "center"
}
})
5、一般而言,一個app我們需要註冊一下才能使用,這個就相當於react的入口。使用的關鍵字是AppRegistry,基本語法就是:
AppRegistry.registerComponent(‘AwesomeProject’, () => App);
其中這個App是一個元件。一般是最外層的入口元件。
當然了,這些僅僅是大體上的一些東西,我們看看細節。
細節一:react、react-native中最重要的兩個概念是prop和state。其中prop是屬性,不可改變,主要用於子元件和父元件的傳值。而state代表狀態,主要用於介面反饋,它的值是可以改變的。改變的方式是this.setState()函式。
那prop到底是怎麼用的呢?
//我們這樣寫父元件
import React , { Component } from 'react';
import { AppRegistry} from 'react-native';
import Child from './Child'
class App extends Component {
render() {
return (
<Child title="hello"></Child>
)
}
}
AppRegistry.registerComponent('AwesomeProject', () => App);
//我們這樣寫子元件
import React,{ Component } from 'react';
import { View,Text,StyleSheet } from 'react-native';
export default class Child extends Component{
render() {
return (
<View>
<Text>{this.props.title}</Text>
</View>
)
}
}
在父元件中我們註冊了App,並且呼叫了子元件Child,給它設定了屬性 title =“hello”,然後在子元件中 {this.props.title} 展示在介面中。
那麼state怎麼使用呢?接著剛才的示例,我們對子元件稍作改變:
import React,{ Component } from 'react';
import { View,Text,Button,StyleSheet,Alert } from 'react-native';
export default class Child extends Component{
constructor(props) {
super(props);
this.state = {
toggle: true
};
}
onToggle() {
//Alert.alert('Button has been pressed!');
this.setState({toggle: !this.state.toggle})
}
render() {
let display = this.state.toggle?this.props.title:"";
return (
<View>
<Text>{display}</Text>
<View>
<Button
onPress={() => this.onToggle()}
title="toggle"
color="#3c78ff"
accessibilityLabel="Learn more about this purple button"
/>
</View>
</View>
)
}
}
這樣我們就可以通過改變toggle的狀態值來進行介面操作(通過操作資料改變介面)。
細節二:onPress事件,相當於我們的click事件。在寫法上需要理解一下。
在上面的Button元件中,我們的onPress事件是這樣寫的。
<Button
onPress={() => this.onToggle()}
title="toggle"
color="#3c78ff"
accessibilityLabel="Learn more about this purple button"
/>
注意:onPress={() => this.onToggle()},這個代表什麼意思呢?
相當於onPress = function(){ //coding }
而不是onPress = (function(){ //coding })();
區別是,一個是函式,一個是執行函式。
那麼我們這樣寫onPress看對不對:
onPress={() => this.onToggle}//明顯不對,因為this.onToggle是一個函式,我們的目的是onPress之後toggle的狀態值改變!!所以後面需要執行,就有();
通過上面的理解,其實onPress還是可以這樣寫:
onPress={this.onToggle.bind(this)}//這樣就符合邏輯
這裡的bind(this)代表我需要把this的指向傳遞下去。為什麼呢?因為this.onToggle不是箭頭函式,而上面的是箭頭函式。
<完>