React Native 入門(七) - ref

當(dāng)前 RN 版本:0.49
操作環(huán)境:Windows 10

ref 可以看做是組件被渲染后,指向組件的一個引用,我們可以通過 ref 來獲取到這個組件的實(shí)例。

下面我們通過一個例子來看一下。

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, {Component} from 'react';
import {
  View,
  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/> 用來顯示當(dāng)前組件里的 age 的大小,以及一個按鈕。

我們給 MyView 設(shè)置了一個 ref 屬性 ref='myView' ,這個名字是任意取的。然后按下按鈕的時候,通過 this.refs.myView 獲取到了 MyView 的實(shí)例并且調(diào)用到了 getAge() 這個方法,這樣我們就獲取到了 MyView 中的 age 的大小。

點(diǎn)擊前

點(diǎn)擊后

上圖是按下按鈕前后的顯示。

另外,用 ref 獲取組件時也有兩種寫法:

this.refs.myView

或者

this.refs['myView']

需要注意第二種方式是需要帶引號的。選擇哪種方式,根據(jù)自己的習(xí)慣來就好,個人喜歡第一種。

文章同步自 CSDN:http://blog.csdn.net/qq_24867873/article/details/78354492

歡迎關(guān)注我的微信公眾號
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容