组装者模式在React Native项目中的一个实战案例
发布时间:2020-12-15 20:32:44 所属栏目:百科 来源:网络整理
导读:前言 在实际的开发中,如果遇到多个组件有一些共性,我们可以提取一个BaseItem出来,然后在多个组件中进行复用,一种方式是通过继承的方式,而今天我们要说的是另一种方式--组装者模式。 什么是组装者模式? 就是在一个类中封装一些共有特性,然后使得在使用
前言在实际的开发中,如果遇到多个组件有一些共性,我们可以提取一个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 } }
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(); } } 当然,以上只是演示了以下基本的使用,在实际中,我们可以去做更多的处理。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |