react-native 之 ref 的使用
发布时间:2020-12-15 07:14:49 所属栏目:百科 来源:网络整理
导读:重点内容 在react-native中可以通过 ref属性来获取组件,并设置组件的属性及其方法,实例如下 class TestRef extends Component { // 构造 constructor(props) { super (props); // 初始状态 this .state = {}; this .changeStyle = this .changeStyle.bind(
重点内容在react-native中可以通过 ref属性来获取组件,并设置组件的属性及其方法,实例如下 class TestRef extends Component {
// 构造
constructor(props) {
super(props);
// 初始状态
this.state = {};
this.changeStyle = this.changeStyle.bind(this);
}
render(){
return(
<View style={{height:50,width:200,backgroundColor:'orange'}} ref='ref_test' >
<Text ref={(e)=>{this._myText = e;}} onPress={this.changeStyle}>change style</Text>
</View>
)
}
changeStyle(){
this.refs.ref_test.setNativeProps({
style:{
backgroundColor:'red',height:100
}
});
this._myText.setNativeProps({
style:{
color:'yellow',}
});
}
}
需要注意点的是 this.changeStyle = this.changeStyle.bind(this);
这个点击的方法需要绑定,如果去掉了,则会报错!经过实验发现,在方法中使用了 this 调用类方法属性的时候,那么这个方法必须绑定了this才可以了,否则方法里面不认识 this 上面演示了设置属性的,还可以执行组件的方法,如果是WebView组件,就可以这样操作 <WebView ref="webView"/>
this.refs.webView.reload();
执行其刷新操作。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |