重点内容在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();
执行其刷新操作。
原文地址:https://www.jb51.cc/react/303651.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。