Props 屬性
import React, {Component} from 'react';
import {Image} from 'react-native';
export default class Bananas extends Component {
render(){
let pic = {
uri: 'https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg'
};
return (
<Image source={pic} style={{width:193,height:110}}/>
);
}
}
- 包圍pic的大括號(hào)的意思是——括號(hào)內(nèi)部是一個(gè)js變量或表達(dá)式,需要執(zhí)行后取值。
我們可以把任何合法的JavaScript表達(dá)式通過(guò)括號(hào)嵌入到JSX語(yǔ)句中
import React, {Component} from 'react';
import {Text, View} from 'react-native';
class Greeting extends Component{
render(){
return (
<View style={{alignItems:'center', marginTop:50}}>
<Text>Hello {this.props.name}</Text>
</View>
)
}
}
export default class Bananas extends Component {
render(){
return (
<View>
<Greeting name='Rexxar'/>
<Greeting name='Jaina'/>
<Greeting name='Valeera'/>
</View>
);
}
}
- 自定義組件Greeting的屬性name,在組件中使用
this.props調(diào)用。 - props是在父組件中對(duì)目標(biāo)組件進(jìn)行指定,且指定后,在目標(biāo)組件的生命周期 屬性值不會(huì)再改變。
tips:代碼示例中多次出現(xiàn)的 View 組件——常用作其他組件的容器,來(lái)幫助控制布局和樣式
State 狀態(tài)
props一經(jīng)指定后,在組件的生命周期中將不再改變,若需要改變的數(shù)據(jù),需要使用state。
import React, {Component} from 'react';
import {Text, View} from 'react-native';
class Blink extends Component{
// 聲明state對(duì)象
state = {isShowingText: true};
// mount時(shí)執(zhí)行函數(shù)
componentDidMount() {
setInterval(()=>{
this.setState({
isShowingText: !this.state.isShowingText
});
}, 1000);
}
render(){
if(!this.state.isShowingText) {
return null;
}
return (
<Text>{this.props.text}</Text>
)
}
}
export default class BlinkApp extends Component {
render(){
return (
<View>
<Blink text='I love to blink'/>
<Blink text='Yes blinking is so great'/>
</View>
);
}
}
- 每次調(diào)用setState(this.state=xx這樣的直接賦值是無(wú)效的),BlinkApp就會(huì)重新執(zhí)行render方法,重新渲染;
- state的工作原理和React.js完全一致,可以參閱React.Component API
- 可以使用一些“狀態(tài)容器”比如Redux來(lái)統(tǒng)一管理數(shù)據(jù)流。
tips:
setState是異步操作,修改不會(huì)馬上生效;
setState是merge操作,僅修改指定的屬性,不會(huì)對(duì)其他屬性產(chǎn)生影響