react native 之setState

react native 版本採用0.33版本。。新版本至關於舊版本有了一部分改動,仍是比較麻煩的,這裏從新開始學習。react

react native 結構:ios

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

class BleManager extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit index.ios.js
        </Text>
        <Text style={styles.instructions}>
          Press Cmd+R to reload,{'\n'}
          Cmd+D or shake for dev menu
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('BleManager', () => BleManager);

這是一個最基礎的代碼結構,react native的精髓就在於state、props,我一直沒搞懂,主要0.33跟之前的版本有些不太同樣了,初始化state必定要這樣寫git

constructor() {  
		super();
    	        this.state = {  
      		    isRefreshing: false,  
      		};  
    	};

在後面的代碼裏面經過setState來修改state來達到修改dom也就是render()裏面的內容代碼結構,這裏能夠看一段代碼github

_onRefresh() { 
	  	this.setState({isRefreshing: true});  
    	setTimeout(() => {  
	      	// 準備下拉刷新的5條數據  
	      	const rowData = Array.from(new Array(5))  
	     		.map((val, i) => ({  
	      		 text: '刷新行 ' + (+this.state.loaded + i)  
	      	})).concat(this.state.rowData);  
	   
	      	this.setState({  
	        	loaded: this.state.loaded + 5,  
	        	isRefreshing: false,  
	        	rowData: rowData,  
	      	});  
	    }, 5000);  
    }

render() {
  		let rows = this.state.rowData.map((row,ii) => {  
	    	return <Row key={ii} data={row}/>;  
	    }); 
	    
   		return (
        	<ScrollView style={styles.scrollview}
		        refreshControl={  
		          	<RefreshControl  
		           		refreshing={this.state.isRefreshing}  
		            	onRefresh={this._onRefresh.bind(this)}  
		            	colors={['#ff0000', '#00ff00','#0000ff','#3ad564']}  
		           		progressBackgroundColor="#ffffff"  
		          	/>  
		        }>  
		        
		        <ViewPager  
				    style={{height:130}}  
				    dataSource={this.state.dataSource}  
				    renderPage={this._renderPage.bind(this)}  
				    isLoop={true}  
				    autoPlay={true}/>  
            	{rows}
            </ScrollView>
    	);
  	}

在0.33之後寫法必定要切記在調用onRefresh={this._onRefresh.bind(this)} ,若是後面沒有bind(this),那麼會對setState提示報錯,問題糾結了好久,OK,今天先就講解state,歡迎你們交流react-native

相關文章
相關標籤/搜索