State(状态)
props和state。props是在父組件中指定,而且一經(jīng)指定,在被指定的組件的生命周期中則不再改變。 對于需要改變的數(shù)據(jù),我們需要使用state。般來說,你需要在constructor中初始化state(譯注:這是ES6的寫法,早期的很多ES5的例子使用的是getInitialState方法來初始化state,這一做法會(huì)逐漸被淘汰),然后在需要修改時(shí)調(diào)用setState方法。
import React, { Component } from 'react'; import { AppRegistry, Text, View } from 'react-native'; class Blink extends Component { constructor(props) { super(props); this.state = { showText: true }; // 每1000毫秒對showText狀態(tài)做一次取反操作 setInterval(() => { this.setState({ showText: !this.state.showText }); }, 1000); } render() { // 根據(jù)當(dāng)前showText的值決定是否顯示text內(nèi)容 let display = this.state.showText ? this.props.text : ' '; return ( <Text>{display}</Text> ); } } class BlinkApp extends Component { render() { return ( <View> <Blink text='I love to blink' /> <Blink text='Yes blinking is so great' /> <Blink text='Why did they ever take this out of HTML' /> <Blink text='Look at me look at me look at me' /> </View> ); } }AppRegistry.registerComponent('BlinkApp', () => BlinkApp);
轉(zhuǎn)載于:https://www.cnblogs.com/dragonh/p/6210605.html
與50位技術(shù)專家面對面20年技術(shù)見證,附贈(zèng)技術(shù)全景圖總結(jié)
- 上一篇: Python语法基础(长期)
- 下一篇: 测试套件