React Native自定義Button

ZY_FlyWay發表於2017-08-21


效果:





引用檔案程式碼:


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定製程式碼:


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;



相關文章