在React Native环境配置成功后,我们创建一个名为AndroidReact的react-native项目。作者的react-native版本为0.29
使用react-native init AndroidReact命令创建react-native项目后,index.android.js或index.ios.js中默认内容为:
/**
* 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 AndroidReact extends Component {
constructor(props){
super(props);
}
render() {
return (
Welcome to React Native!
To get started, edit index.android.js
Shake or press menu button for dev menu
);
}
}
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('AndroidReact', () => AndroidReact);
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TouchableHighlight
} from 'react-native';
render() {
return (
Welcome to React Native!
To get started, edit index.android.js
Shake or press menu button for dev menu
Button
);
}
我们将TouchableHighlight的点击事件交给
_onPressButton函数处理,所以需要在AndroidReact类中添加函数:
_onPressButton(){
}
我们首先在constructor(props)函数中添加AndroidReact内部变量index:
constructor(props){
super(props);
this.state = {index:0};
}
在_onPressButton函数中改变index的值:
_onPressButton(){
this.setState({index: this.state.index + 1});
}
然后在视图中加入index的值:
Button {this.state.index}
原因是_onPressButton()函数中找不到this.state.index。this应该指向AndroidReact类,由于_onPressButton()函数找不到this的指向导致了错误的发生。
所以,我们需要给_onPressButton()绑定this指针。在constructor函数中为_onPressButton()绑定:
constructor(props){
super(props);
this.state = {index:0};
this._onPressButton = this._onPressButton.bind(this);
}
效果,点击前:
点击后:
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TouchableHighlight
} from 'react-native';
class AndroidReact extends Component {
constructor(props){
super(props);
this.state = {index:0};
this._onPressButton = this._onPressButton.bind(this);
}
componentDidMount(){
}
_onPressButton(){
this.setState({index: this.state.index + 1});
}
render() {
return (
Welcome to React Native!
To get started, edit index.android.js
Shake or press menu button for dev menu
Button {this.state.index}
);
}
}
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('AndroidReact', () => AndroidReact);