react native中state和ref的使用
因props是只讀的,頁面中需要交互的情況我們就需要用到state。
一、如何使用state
1:初始化state
第一種方式:
constructor(props) { super(props) console.log('_____constructor_____') this.state = { count: 0 } } render() { return ( <View> 點擊增加 {this.state.count} </View> ); }
第二種方式:
state = { count: 0 } render() { return ( <View> 點擊增加 {this.state.count} </View> ); }
例子:點擊增大或減小氣球的小例子
import { Text, View, Image } from 'react-native'; constructor(props) { super(props) console.log('_____constructor_____') this.state = { size: 40 } } render() { return ( <View> <Text onPress = {() =>{ this.setState({ size: this.state.size+10 }) }}> 點擊增加 </Text> <Image style={{width:this.state.size,height:this.state.size}} source={require('./1.png')} > </Image> <Text onPress = {() =>{ this.setState({ size: this.state.size-10 }) }}> 點擊減小 </Text> </View> ); }
二、ref的使用
組件中定義ref的值:
<MyComponent ref='myRef'/>
獲取ref的值
this.refs.myRef
注意:這里的this.refs.myRef就是組件實例,可以獲取到實例的屬性和方法
例子:
1:利用ref觸發子組件的方法
子組件中定義一個方法:
refFun() { console.log(123) }
父組件中調用
<View> <MyComponent ref='myRef'/> <Text onPress={() => { this.refs.myRef.refFun() }}>點擊輸出值</Text> </View>