zoukankan      html  css  js  c++  java
  • 组装者模式在React Native项目中的一个实战案例

    前言

    在实际的开发中,如果遇到多个组件有一些共性,我们可以提取一个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();
        }
    }
    
    

    当然,以上只是演示了以下基本的使用,在实际中,我们可以去做更多的处理。

  • 相关阅读:
    检测数组和对象&扩展String.prototype.format 字符串拼接的功能
    10000以内unicode对照表
    手机页面加载完成后再显示(粗糙版)
    手机端网页 横竖屏翻转事件
    代替eval的方法
    跨域和非跨域 获取iframe页面高度的方法
    HDU2032 杨辉三角
    HDU2030 汉字统计
    POJ 2029 Palindromes _easy version
    POJ3468 A Simple Problem with Integers
  • 原文地址:https://www.cnblogs.com/fe-linjin/p/10659287.html
Copyright © 2011-2022 走看看