React Native 入门(七) - ref
发布时间:2020-12-15 06:43:47 所属栏目:百科 来源:网络整理
导读:当前 RN 版本:0.49 操作环境:Windows 10 ref 可以看做是组件被渲染后,指向组件的一个引用,我们可以通过 ref 来获取到这个组件的实例。 下面我们通过一个例子来看一下。 MyView.js: import React,{Component} from 'react' ; import { View,Text} from '
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>
}
}
在这个组件中,我们只渲染了一行文本。然后写了一个 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 设置了一个 ref 属性 上图是按下按钮前后的显示。 另外,用 ref 获取组件时也有两种写法: this.refs.myView
或者 this.refs['myView']
需要注意第二种方式是需要带引号的。选择哪种方式,根据自己的习惯来就好,个人喜欢第一种。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |