Skip to content

Latest commit

 

History

History
39 lines (34 loc) · 847 Bytes

4.state.md

File metadata and controls

39 lines (34 loc) · 847 Bytes

State

  • Component 內部的狀態
  • 透過 this.state 可拿到 State 物件
  • 跟變數不同,當 State 改變會觸發 React Render
  • 直接改變 State 不會觸發 Render,要使用 this.setState 來觸發

Sample: https://snack.expo.io/S19lxDFF-

import React, { Component, PropTypes } from 'react';
import { View, Text, TouchableOpacity } from 'react-native';

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      title: '標題'
    }
  }
  
  render() {
    return (
      <View>
        <TouchableOpacity onPress={() => {
          this.setState({
            title: 'Update State Success'
          })
        }}>
          <Text>更新 State</Text>
        </TouchableOpacity>
        <Text>
          {this.state.title}
        </Text>
      </View>
    );
  }
}