ReactNative自定义控件状态更新的正确姿势

本文探讨了ReactNative自定义控件中状态更新的正确方法,针对属性如颜色等无法即时更新导致界面不刷新的问题,提供了解决方案。

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

ReactNative自定义控件状态更新的正确姿势

我们经常要自定义一个ReactNative控件,而在Render()方法中会用到组件的属性,而这些属性不能即时更新,导致界面不能刷新。举例如下:

比如我们定义了一个按钮组件,这个组件外部会指定一个颜色,我们在构造方法中初始化当前的属性borderColor为this.props.borderColor;

'use strict'
import React, {Component} from 'react';
import {
    View, Text, TouchableOpacity
} from 'react-native';

export default class Button extends Component {

    constructor(props) {
        super(props);
        this.state = {
            borderColor : this.props.borderColor || "#FF0000"
        }
    }

    componentWillReceiveProps(nextProps) {
        if(nextProps.borderColor != this.borderColor){
            this.setState({
                borderColor : nextProps.borderColor
            });
        }
    }

    render() {
        return (<TouchableOpacity onPress = { this.props.onPress }>
            <View style={ [{
                borderWidth: 1,
                borderColor: this.state.borderColor,
                justifyContent:"center",
            }, this.props.style]}>

                <Text style = {
                    {
                    textAlign : "center",
                    textAlignVertical: "center" ,
                    alignSelf:"center",flex:1} } >
                    { this.props.text }
                </Text>

            </View>
        </TouchableOpacity>);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值