react native Back 按钮封装

来源:互联网 发布:淘宝奢侈品拍卖真假 编辑:程序博客网 时间:2024/06/04 17:55

项目中返回按钮出现的频率非常高,所以我们封装一个Back按钮,基本要求如下:

传入图片资源作为按钮图片
可以设置点击区域style和图片style
点击回调函数
传入react-navigation 的navigation,点击直接goBack

/** * Created by on 2017/3/27. */import React, {Component, PropTypes} from 'react';import {    StyleSheet,    Image,} from 'react-native';import Touchable from './Touchable';export default class Back extends Component {    static propTypes = {        //图片资源        source: PropTypes.oneOfType([            PropTypes.shape({                uri: PropTypes.string,                headers: PropTypes.objectOf(PropTypes.string),            }),            // Opaque type returned by require('./image.jpg')            PropTypes.number,            // Multiple sources            PropTypes.arrayOf(                PropTypes.shape({                    uri: PropTypes.string,                    width: PropTypes.number,                    height: PropTypes.number,                }))        ]),        imageStyle: Image.style,        onPress: PropTypes.func,    }    _onPress = () => {        const {navigation} = this.props;        if (navigation) {            navigation.goBack();        }        const {onPress} = this.props;        if (onPress) {            onPress();        }    }    render() {        var props = Object.assign({}, this.props);        props.imageStyle = [styles.image, props.imageStyle];        return (            <Touchable style={props.style}                       onPress={this._onPress}>                <Image style={props.imageStyle} source={this.props.source}/>            </Touchable>        );    }}const styles = StyleSheet.create({        image: {        },    })

Touchable 是我封装的另一个控件,地址:http://blog.csdn.net/mengks1987/article/details/70242842

demo

<Back style={{width:56,height:44}} imageStyle={{width:20,height:16}} source={require('../back.png')} navigation={this.props.navigation}/>
原创粉丝点击