当前 RN 版本:0.49
操作环境:Windows 10
ref 可以看做是组件被渲染后,指向组件的一个引用,我们可以通过 ref 来获取到这个组件的实例。
下面我们通过一个例子来看一下。
MyView.js:
- import React,{Component} from 'react';
- import {
- View,Text
- } from 'react-native';
-
- export default class MyView extends Component {
-
- static defaultProps = {
- age: 22
- }
-
- constructor(props) {
- super(props)
- this.state = {
- age: this.props.age
- }
- }
-
- getAge() {
- return this.state.age;
- }
-
- render() {
- return <View>
- <Text
- style={{textAlign: 'center',fontSize: 20}}>
- 小明的年龄是:
- </Text>
- </View>
- }
- }
在这个组件中,我们只渲染了一行文本。然后写了一个 getAge()
的方法,用来返回 age 的大小。
App.js:
- import React,Text,Button
- } from 'react-native';
- import MyView from './MyView';
-
- export default class App extends Component<{}> {
-
- constructor(props) {
- super(props);
- this.state = {
- age: 0
- }
- }
-
- render() {
- return <View>
- <MyView ref='myView'/>
- <Text
- style={{textAlign: 'center',fontSize: 20}}>
- {this.state.age}
- </Text>
- <Button
- title={'获取年龄'}
- onPress={() => {
- var age = this.refs.myView.getAge();
- this.setState({
- age: age
- })
- }}/>
- </View>
- }
- }
这里我们渲染了三个组件:一个 <MyView/>
,一个 <Text/>
用来显示当前组件里的 age 的大小,以及一个按钮。
我们给 MyView 设置了一个 ref 属性 ref='myView'
,这个名字是任意取的。然后按下按钮的时候,通过 this.refs.myView
获取到了 MyView 的实例并且调用到了 getAge()
这个方法,这样我们就获取到了 MyView 中的 age 的大小。
上图是按下按钮前后的显示。
另外,用 ref 获取组件时也有两种写法:
- this.refs.myView
或者
- this.refs['myView']
需要注意第二种方式是需要带引号的。选择哪种方式,根据自己的习惯来就好,个人喜欢第一种。