react-native 之 ref 的使用

重点内容在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();

执行其刷新操作。

相关文章

一、前言 在组件方面react和Vue一样的,核心思想玩的就是组件...
前言: 前段时间学习完react后,刚好就接到公司一个react项目...
前言: 最近收到组长通知我们项目组后面新开的项目准备统一技...
react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...