close

13.png

props和state是資料控制組件,props為父類別, 在組件內都的生命週期為固定,要更改資料就必須使用state,正常來說,state在構造函數中初始化後,在要更改資料的地方使用setState

這裡以文字閃爍為例,閃爍的組件被創建時,文字本身被設置一次,因此文字本身就是一個prop,而文字顯示或隱藏狀態,保存在state裡

接下來修改在[筆記]安裝React-Native與創造第一個專案,所創造的專案來演示此功能

01.JPG

class Glint extends Component {
  /* 設置文字狀態,每一秒改變一次 */    
  constructor(props) {
    super(props);//呼叫對應的父類別建構元,props
    this.state = {showText: true};//狀態初始化,showText變數為true
    
    /* 使用setState,每一秒執行一次更改資料 */
    setInterval(() => {
      this.setState(previousState => {
        return { showText: !previousState.showText };//每一秒更改showText狀態,true或false
      });
    }, 1000);
  }

  render() {
    /* 當state狀態為true,顯示文字,反之為false就顯示空白,也就是隱藏文字 */
    let display = this.state.showText ? this.props.text : ' ';
    return (
      <Text>{display}</Text>
    );
  }
}

export default class AwesomeProject extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Glint text='Hello,world!'/>
        <Glint text='Hi,Michael Jheng!'/>
      </View>
    );
  }
}

在Node.js command prompt執行"react-native run-android",即可安裝在模擬器或手機上演示,

文字顯示

03.JPG

文字隱藏

02.JPG

arrow
arrow

    鄭智遠 發表在 痞客邦 留言(0) 人氣()