ReactNative 中 Component 的組成
Component 組件
定義(ES6 Class 的形式定義):
class CustomButton extends React.Component<{},{}> { render() { //渲染入口 return (<View></View>) } } 注:Component 的泛型類型爲 Component<P,S>,分別爲屬性 Props 和狀態State,暫時傳入空對象{},後面會詳細解讀。
樣式(Style)(CSS)
所有的核心組件都接受名爲 style 的屬性,用來確定當前控件的 UI 樣式。
它接受傳入對象或者數組(數組中後面的樣式優先級更高)。
爲了便於查閱和管理,建議使用 StyleSheet.create 來集中定義組件樣式。import * as React from 'react'; import {Text, StyleSheet, View} from "react-native"; export default class CustomButton extends React.Component<{}, {}> { render() { return ( <View> <Text style={styles.textObject}>Object</Text> <Text style={[styles.textObject, styles.textArray]}>Array</Text> </View> ) } } const styles = StyleSheet.create({ textObject: { width: 100, height: 100, color: 'blue' }, textArray: { fontSize: 20, color: 'red' } });
屬性(Props)(只讀)
外部組件通過傳值的方式,定製內部組件的樣式或處理邏輯的參數叫做屬性。import * as React from 'react'; import {Text, TouchableOpacity} from "react-native"; interface Props { btnStyle: any btnText: string btnPress: () => void } class CustomButton extends React.Component<Props, {}> { render() { return ( <TouchableOpacity onPress={this.props.btnPress}> <Text style={this.props.btnStyle}> {this.props.btnText} </Text> </TouchableOpacity> ) } }
狀態更新(State)(私有)
內部組件通過動態修改State,主動觸發組件的render()方法實現UI的重新渲染。import * as React from 'react'; import {Text} from "react-native"; interface State { count: number } class CustomButton extends React.Component<{}, State> { private _interval: number; constructor(props: any) { super(props); // State需要初始化 this.state = { count: 0 }; // 設置定時器,每1s數字+1 this._interval = setInterval(() => { // 動態修改State this.setState({ count: this.state.count + 1 }) }, 1000); } /** 組件銷燬時清理計時器 */ componentWillUnmount() { clearInterval(this._interval); } render() { return ( <Text style={{width: 100, height: 100}}> {this.state.count} </Text> ) } }