一、根據state的值動態改變佈局
import React, { Component,PropTypes } from 'react';
import {
StyleSheet,
Text,
View,
Image,
TouchableOpacity,
Dimensions,
Platform,
Alert,
ToastAndroid,
TextInput,
} from 'react-native';
import ulity from './ulity';
class SatisfactionSurvey extends Component {
constructor(props) {
super(props)
this.state = {
star:false,
};
}
render() {
return(
<View style={styles.container}>
<TouchableOpacity onPress ={
() => {
this.setState({
star:true,
})
}
}>
{
this.state.star == true?(
<Image style={[{marginTop:0},{marginLeft:11,width:18,height:17}]}
source={require('./images/star.png')}
/>
):(
<Image style={[{marginTop:0},{marginLeft:11,width:18,height:17}]}
source={require('./images/unstar.png')}
/>
)
}
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flexDirection:'row',
marginTop:21,
},
textStyle:{
color:'rgba(102,102,102,1)',
width:90,
fontSize:15,
marginLeft:22,
}
});
module.exports = SatisfactionSurvey;
state 屬性主要用來存儲組件自身需要的數據,我們一般通過修改 state 屬性的值來更新數據,react native 內部會監聽 state 的變化,一旦發生變化就會主動觸發組件的 render() 方法來更新 UI,就是說state值得變化可以刷新佈局。
一般情況下,使用這個state是再constructor()方法中初始化如上面的
constructor(props) {
super(props)
this.state = {
star:false,
};
}
在需要刷新UI的地方改變這個值就可以,如:
this.setState({
star:true,
})
state裏面變量的值只能是用this.setState方法來改變。
上面代碼適合做類似於狀態選擇器這類的效果。
二、list數據的動態佈局
當然針對list的數據用listview來佈局也是沒問題的。
render() {
return(
<View style={styles.container}>
{
dataList.map((elem,key)=>{
return (<SatisfactionSurveyItem
key={key}
style={{marginLeft:30,marginTop:13,marginRight:30}}
elemData ={elem}
/>)
})
}
}
這個代碼實現跟用listview佈局效果是一樣的, key={key}這個是爲了解決出現的Each child in an array or iterator should have a unique “key” prop警告,對於這個警告原因是:react對dom做遍歷的時候,會根據data-reactid生成虛擬dom樹。如果你沒有手動的添加unique constant key的話,react是無法記錄你的dom操作的。它只會在重新渲染的時候,繼續使用相應dom數組的序數號(就是array[index]這種)來比對dom樹。錯誤說得很清楚,就是缺一個叫做key的東西,就是遍歷的時候隨便給item傳個key值就可以了。