1. 程式人生 > >組裝者模式在React Native項目中的一個實戰案例

組裝者模式在React Native項目中的一個實戰案例

ops 多個 靈活 實戰 一個 some true ams 開發

前言

在實際的開發中,如果遇到多個組件有一些共性,我們可以提取一個BaseItem出來,然後在多個組件中進行復用,一種方式是通過繼承的方式,而今天我們要說的是另一種方式--組裝者模式。

什麽是組裝者模式?

就是在一個類中封裝一些共有特性,然後使得在使用的組件中,可以動態的去添加一些屬性或者行為,相比較於繼承來說,組裝者模式會更加的靈活。

實例演示

/**
 *  AboutCommon.js
 *  組裝者模式 模仿一些生命周期函數
 */
export default class AboutCommon {
    constructor(props, updateState) {
        this.props = props;
        this.updateState = updateState;
        this.backPress = new BackPressComponent({ backPress: () => this.onBackPress() });
        
    }

    componentDidMount() {
        this.backPress.componentDidMount(); 
    }

    componentWillUnmount() {
        this.backPress.componentWillUnmount();
    }
    /** 處理Android中的物理返回鍵 */
    onBackPress = () => {
        NavigationUtil.goBack(this.props.navigation);
        return true;
    }

    render() {
        ....do something
    }
}

然後在AboutPage.js中使用它,通過在constuctor中實例化對象,成為當前組件中的一個成員,然後使用所需要的,以下只演示了一小部分功能,比如處理Android中的物理返回鍵功能

export default class AboutPage extends Component<Props> {
    constructor(props) {
        super(props);
        this.params = this.props.navigation.state.params;
        this.aboutCommon = new AboutCommon({
            ...this.params,
            navigation: this.props.navigation,
            flagAbout: FLAG_ABOUT.flag_about
        }, data => this.setState({ ...data }))
        this.state = {
            data: config
        }
    }
    
    componetDidMount() {
        this.aboutCommon.componetDidMount();
    }

    componetWillUnmount() {
        this.aboutCommon.componetWillUnmount();
    }
}

當然,以上只是演示了以下基本的使用,在實際中,我們可以去做更多的處理。

組裝者模式在React Native項目中的一個實戰案例