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

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>);
    }
}

猜你喜欢

转载自blog.csdn.net/chenzhen200638/article/details/78355389