React Native 筆記之Props、State、Ref使用
阿新 • • 發佈:2018-11-11
Props
props是React元件的輸入內容。 它們是從父元件傳遞給子元件的資料。props 是隻讀的。 不應該以任何方式修改它們.
程式碼示例:
import React, { Component ,PropTypes} from 'react'; import { AppRegistry, StyleSheet, Text, View, WebView } from 'react-native'; export default class Shop extends Component { /// 設定預設的屬性值 static defaultProps = { name:"小明", age:13 } /// 屬性的型別檢查 static propTypes = { name:PropTypes.string.isRequired(),/// 必須傳遞的 age:PropTypes.age } render() { return ( <View style={styles.container}> /* * 父元件傳值則為傳過來的值 否則為預設值 * */ <Text>{this.props.name} {this.props.age}</Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, });
State
我們使用兩種資料來控制一個元件:props和state。props是在父元件中指定,而且一經指定,在被指定的元件的生命週期中則不再改變。 對於需要改變的資料,我們需要使用state。
一般來說,你需要在 constructor 中初始化state(譯註:這是 ES6 的寫法,早期的很多 ES5 的例子使用的是 getInitialState 方法來初始化 state,這一做法會逐漸被淘汰),然後在需要修改時呼叫setState方法.
程式碼示例
import React, { Component ,PropTypes} from 'react'; import { AppRegistry, StyleSheet, Text, View, WebView } from 'react-native'; export default class Shop extends Component { // 初始狀態 // state ={ // size:80 // } // 構造 constructor(props) { super(props); // 初始狀態 this.state = { size:80, }; } render() { return ( <View style={styles.container}> <Text>{this.state.size} </Text> <Text onPress={()=>{ this.setState = ({ size:this.state.size+10 }) }}>增加</Text> </View> ); } }
Ref
元件並不是真實的 DOM 節點,而是存在於記憶體之中的一種資料結構,叫做虛擬 DOM (virtual DOM)。只有當它插入文件以後,才會變成真實的 DOM 。根據 React 的設計,所有的 DOM 變動,都先在虛擬 DOM 上發生,然後再將實際發生變動的部分,反映在真實 DOM上,這種演算法叫做 DOM diff ,它可以極大提高網頁的效能表現。
但是,有時需要從元件獲取真實 DOM 的節點,這時就要用到 ref 屬性。
程式碼示例
class CustomTextInput extends React.Component { constructor(props) { super(props); // 建立 ref 儲存 textInput DOM 元素 this.textInput = React.createRef(); this.focusTextInput = this.focusTextInput.bind(this); } focusTextInput() { // 直接使用原生 API 使 text 輸入框獲得焦點 // 注意:通過 "current" 取得 DOM 節點 this.textInput.current.focus(); } render() { // 告訴 React 我們想把 <input> ref 關聯到構造器裡建立的 `textInput` 上 return ( <div> <input type="text" ref={this.textInput} /> <input type="button" value="Focus the text input" onClick={this.focusTextInput} /> </div> ); } }