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={{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>