State(状态)
props和state。props是在父組件中指定,而且一經指定,在被指定的組件的生命周期中則不再改變。 對于需要改變的數據,我們需要使用state。般來說,你需要在constructor中初始化state(譯注:這是ES6的寫法,早期的很多ES5的例子使用的是getInitialState方法來初始化state,這一做法會逐漸被淘汰),然后在需要修改時調用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狀態做一次取反操作 setInterval(() => { this.setState({ showText: !this.state.showText }); }, 1000); } render() { // 根據當前showText的值決定是否顯示text內容 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);
轉載于:https://www.cnblogs.com/dragonh/p/6210605.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
- 上一篇: Python语法基础(长期)
- 下一篇: 测试套件