react-native 之 ref 的使用

本文介绍了如何在React Native中利用Refs获取组件实例并修改样式及触发组件方法,提供了具体示例,包括设置组件样式和刷新WebView组件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

重点内容在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',width:200,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();

执行其刷新操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值