React Native 入门(七) - ref

前端之家收集整理的这篇文章主要介绍了React Native 入门(七) - ref前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

当前 RN 版本:0.49
操作环境:Windows 10

ref 可以看做是组件被渲染后,指向组件的一个引用,我们可以通过 ref 来获取到这个组件的实例。

下面我们通过一个例子来看一下。

MyView.js:

  1. import React,{Component} from 'react';
  2. import {
  3. View,Text
  4. } from 'react-native';
  5.  
  6. export default class MyView extends Component {
  7.  
  8. static defaultProps = {
  9. age: 22
  10. }
  11.  
  12. constructor(props) {
  13. super(props)
  14. this.state = {
  15. age: this.props.age
  16. }
  17. }
  18.  
  19. getAge() {
  20. return this.state.age;
  21. }
  22.  
  23. render() {
  24. return <View>
  25. <Text
  26. style={{textAlign: 'center',fontSize: 20}}>
  27. 小明的年龄是:
  28. </Text>
  29. </View>
  30. }
  31. }

在这个组件中,我们只渲染了一行文本。然后写了一个 getAge()方法,用来返回 age 的大小。

App.js:

  1. import React,Text,Button
  2. } from 'react-native';
  3. import MyView from './MyView';
  4.  
  5. export default class App extends Component<{}> {
  6.  
  7. constructor(props) {
  8. super(props);
  9. this.state = {
  10. age: 0
  11. }
  12. }
  13.  
  14. render() {
  15. return <View>
  16. <MyView ref='myView'/>
  17. <Text
  18. style={{textAlign: 'center',fontSize: 20}}>
  19. {this.state.age}
  20. </Text>
  21. <Button
  22. title={'获取年龄'}
  23. onPress={() => {
  24. var age = this.refs.myView.getAge();
  25. this.setState({
  26. age: age
  27. })
  28. }}/>
  29. </View>
  30. }
  31. }

这里我们渲染了三个组件:一个 <MyView/> ,一个 <Text/> 用来显示当前组件里的 age 的大小,以及一个按钮。

我们给 MyView 设置了一个 ref 属性 ref='myView' ,这个名字是任意取的。然后按下按钮的时候,通过 this.refs.myView 获取到了 MyView 的实例并且调用到了 getAge() 这个方法,这样我们就获取到了 MyView 中的 age 的大小。


上图是按下按钮前后的显示

另外,用 ref 获取组件时也有两种写法:

  1. this.refs.myView

或者

  1. this.refs['myView']

需要注意第二种方式是需要带引号的。选择哪种方式,根据自己的习惯来就好,个人喜欢第一种。

猜你在找的React相关文章