react-native 之 ref 的使用

太过爱你忘了你带给我的痛 2022-06-01 01:22 568阅读 0赞

react-native 之 ref 的使用,在react-native中可以通过 ref属性来获取组件,并设置组件的属性及其方法,实例如下










1


2


3


4


5


6


7


8


9


10


11


12


13


14


15


16


17


18


19


20


21


22


23


24


25


26


27


28


29


30



class
TestRef
extends
Component {


    
// 构造


    
constructor(props) {


        
super
(props);


        
// 初始状态


        
this
.state = {};


        
this
.changeStyle =
this
.changeStyle.bind(
this
);


 


    
}


    
render(){


        
return
(


            
<view ref=
“ref_test”
style=
“{ {height:50,width:200,backgroundColor:’orange’}}”
>


                
<text ref=
“{(e)=”
>{
this
._myText = e;}}


onPress={
this
.changeStyle}>change style</text>


            
</view>


        
)


    
}


    
changeStyle(){


        
this
.refs.ref_test.setNativeProps({


            
style:{


                
backgroundColor:
‘red’
,width:
200
,height:
100


            
}


        
});


 


        
this
._myText.setNativeProps({


            
style:{


                
color:
‘yellow’
,


            
}


        
});


    
}


}

需要注意点的是










1



this
.changeStyle =
this
.changeStyle.bind(
this
);

这个点击的方法需要绑定,如果去掉了,则会报错!

上面演示了设置属性的,还可以执行组件的方法,如果是WebView组件,就可以这样操作










1



<webview ref=
“webView”
></webview>










1



this
.refs.webView.reload();

执行其刷新操作。

发表评论

表情:
评论列表 (有 0 条评论,568人围观)

还没有评论,来说两句吧...

相关阅读

    相关 vue学习笔记:ref和$refs使用

    ue中有一个特殊的属性ref,可以给每一个标签使用,用来获取标签的元素,和jquery中给标签添加一个class或者id,然后在获取这个标签的元素一样,每一个标签可以根据...