react native 版本采用0.33版本。。新版本相当于旧版本有了一部分改动,还是比较麻烦的,这里重新开始学习。
react native 结构:
/**
* 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一定要这样写
constructor() {
super();
this.state = {
isRefreshing: false,
};
};
在后面的代码里面通过setState来修改state来达到修改dom也就是render()里面的内容代码结构,这里可以看一段代码
_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,欢迎大家交流