React Native知識11-Props(屬性)與State(狀態),react11-props
一:Props(屬性)
大多數組件在建立時就可以使用各種參數來進行定製。用於定製的這些參數就稱為props(屬性)。props是在父組件中指定,而且一經指定,在被指定的組件的生命週期中則不再改變
通過在不同的情境使用不同的屬性定製,可以盡量提高自訂群組件的複用範疇。只需在render函數中引用this.props,然後按需處理即可。下面是一個例子:
import React, { Component } from 'react';import { AppRegistry, Text, View } from 'react-native';class Greeting extends Component { render() { return ( <Text>Hello {this.props.name}!</Text> ); }}class LotsOfGreetings extends Component { render() { return ( <View style={{alignItems: 'center'}}> <Greeting name='Rexxar' /> <Greeting name='Jaina' /> <Greeting name='Valeera' /> </View> ); }}AppRegistry.registerComponent('LotsOfGreetings', () => LotsOfGreetings);
二:State(狀態)
我們使用兩種資料來控制一個組件:props和state。props是在父組件中指定,而且一經指定,在被指定的組件的生命週期中則不再改變。 對於需要改變的資料,我們需要使用state。
一般來說,你需要在constructor中初始化state(譯註:這是ES6的寫法,早期的很多ES5的例子使用的是getInitialState方法來初始化state,這一做法會逐漸被淘汰),然後在需要修改時調用setState方法。
假如我們需要製作一段不停閃爍的文字。文字內容本身在組件建立時就已經指定好了,所以文字內容應該是一個prop。而文字的顯示或隱藏的狀態(快速的顯隱切換就產生了閃爍的效果)則是隨著時間變化的,因此這一狀態應該寫到state中。
import React, { Component } from 'react';import { AppRegistry, Text, View } from 'react-native';class Blink extends Component { constructor(props) { super(props); this.state = { showText: true }; // 每1000毫秒對showText狀態做一次取反操作 setInterval(() => { this.setState({ showText: !this.state.showText }); }, 1000); } render() { // 根據當前showText的值決定是否顯示text內容 let display = this.state.showText ? this.props.text : ' '; return ( <Text>{display}</Text> ); }}class BlinkApp extends Component { render() { return ( <View> <Blink text='I love to blink' /> <Blink text='Yes blinking is so great' /> <Blink text='Why did they ever take this out of HTML' /> <Blink text='Look at me look at me look at me' /> </View> ); }}AppRegistry.registerComponent('BlinkApp', () => BlinkApp);
執行個體2:
import React, { Component } from 'react';import { AppRegistry, Text, TextInput, View } from 'react-native';class PizzaTranslator extends Component { constructor(props) { super(props); this.state = {text: ''}; } render() { return ( <View style={{padding: 10}}> <TextInput style={{height: 40}} placeholder="Type here to translate!" onChangeText={(text) => this.setState({text})} /> <Text style={{padding: 10, fontSize: 42}}> {this.state.text.split(' ').map((word) => word && '