React Native动态布局

来源:互联网 发布:施耐德变频器调试软件 编辑:程序博客网 时间:2024/06/01 08:09

一、根据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值就可以了。

原创粉丝点击