React Native动态布局

本文介绍了如何在React Native中利用state进行动态布局的调整。首先,详细阐述了state的使用,当state值改变时,组件会自动触发render()方法更新UI。接着,讨论了在处理list数据时,如何运用ListView实现动态布局,并提到了key属性的重要性,解决遍历警告,确保React正确地跟踪和更新DOM元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值