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>
);
}
}