React Native運作簡單例子

Create testProject,把下面的code貼在index.android.js / index.ios.js上,然後Run一次看看

  1. x=0,y=0,z=0
  2. constructor的this.state裡set了number: 0, zero: true
  3. x++ 放在componentWillMount
  4. y++ 放在render
  5. z++ 放在componentDidMount
  6. 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);

results matching ""

    No results matching ""