React Native運作簡單例子
Create testProject,把下面的code貼在index.android.js / index.ios.js上,然後Run一次看看
- x=0,y=0,z=0
- constructor的this.state裡set了number: 0, zero: true
- x++ 放在componentWillMount
- y++ 放在render
- z++ 放在componentDidMount
- number: this.state.number+1, zero: false,放在addStateNumber(自訂method)
按幾次"+Add",觀察其變化
'use strict';
import React, { Component } from 'react';
import { AppRegistry,StyleSheet,Text,View,Button } from 'react-native';
let x=0,y=0,z=0;
export default class testProject extends Component {
constructor(props) {
super(props);
this.state = {
number: 0,
zero: true,
};
}
componentWillMount() {
console.log("componentWillMount");
x++;
}
render() {
console.log("render");
y++;
return (
<View style={styles.container}>
<Text>X equals to {x}</Text>
<Text>Y equals to {y}</Text>
<Text>Z equals to {z}</Text>
<Text>State Number equals to {this.state.number}</Text>
{(this.state.number==0? <Text>Zero</Text>:<Text>!!!</Text>)}
{(!this.state.zero? <Text>!!!2</Text>:<Text>Zero2</Text>)}
<Button
onPress={this.addStateNumber.bind(this)}
title="+Add"
color="#841584"
/>
</View>
);
}
componentDidMount() {
console.log("componentDidMount");
z++;
}
addStateNumber(){
console.log("addStateNumber");
this.setState({
number: this.state.number+1,
zero: false,
})
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
});
AppRegistry.registerComponent('testProject', () => testProject);