react-native 之 ref 的使用
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(); |
执行其刷新操作。
还没有评论,来说两句吧...