React Native自定义Button

2019-01-15 15:27:05 浏览数 (1)

效果:

引用文件代码:

代码语言:javascript复制
import React, { Component } from 'react';
import {
   AppRegistry,
  Image,
    Text,
    View,
  StyleSheet,
} from 'react-native';

var ZYButton = require('./ZYButton')

class RNHybrid extends Component {
  render() {
    return(
        <View style={{marginTop:100,alignItems:'center'}}>
              <ZYButton
          clickBtn={()=>this.buttonClick()}
          btnStyle={styles.btnStyle}
          btnInnerTextStyle={styles.btnStyle}
           title="ZYButton"
           />
        </View>
      );   
  }

  buttonClick(){
    alert('buttonClick');
  }
};



const styles = StyleSheet.create({
    btnInnerTextStyle:{
       
    },

    btnStyle:{

    }
});


AppRegistry.registerComponent('RNHybrid', () => RNHybrid);

ZYButton定制代码:

代码语言:javascript复制
import React, { Component, PropTypes} from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    TouchableOpacity
} from 'react-native';


export default class ZYButton extends Component {
    // 对外开放属性
    static propTypes = {
        // 常用的属性
        title: PropTypes.string,
        bgImage:PropTypes.func,
        btnStyle: View.propTypes.style,
        btnInnerTextStyle:Text.propTypes.style,

        // 响应事件
        clickBtn: PropTypes.func
    };

    static defaultProps = {
        clickBtn(){},
        bgImage(){}
    };


    constructor(props){
        super(props);

        this.state = {
            selected:this.props.selected
        }
    }


    render() {
        return (
           <TouchableOpacity
               style={[styles.btnViewStyle, this.props.btnStyle]}
               onPress={()=>this.props.clickBtn()}
           >
               {this.props.bgImage()}
               <Text style={[styles.btnTextStyle, this.props.btnInnerTextStyle]}>{this.props.title}</Text>
           </TouchableOpacity>
        );
    }
}

const styles = StyleSheet.create({
    btnViewStyle:{
        backgroundColor:'red',
        width:120,
        height:40,
        justifyContent:'center',
        alignItems:'center',
        borderRadius:5
    },

    btnTextStyle:{
        color:'#fff',
        fontSize:16,
        backgroundColor:'transparent'
    }
});

module.exports = ZYButton;

0 人点赞