组装者模式在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();
    }
}

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

posted @ 2019-04-05 17:40  林璡  阅读(421)  评论(0编辑  收藏  举报