1. 程式人生 > 實用技巧 >react native 自定義Button元件以及事件

react native 自定義Button元件以及事件

1.建立自定義CKButton.js元件類

 1 import React,{Component} from 'react';
 2 import {
 3     View,
 4     StyleSheet,
 5     Button,
 6     TouchableOpacity,
 7     Text
 8 } from 'react-native';
 9 
10 export default class CKButton extends Component{
11     constructor(){
12         super();
13     }
14     render(){
15 return( 16 <View style={{justifyContent:'center',alignItems:'center'}}> 17 <Button 18 title="登入" 19 onPress={()=>this._onBtnPress()} 20 color="red" 21 /> 22 <TouchableOpacity
23 style={styles.btnStyle} 24 activeOpacity={0.6} 25 onPress={()=>this._onBtnPress()} 26 onPressIn={()=>this._onBtnPress()}//按下按鈕事件 27 onPressOut={()=>this._onBtnPress()}//抬起按鈕事件 28 onLongPress={()=>this
._onBtnPress()}//長按按鈕事件 29 > 30 <Text style={{fontSize:25,color:'green'}}>註冊賬號</Text> 31 </TouchableOpacity> 32 </View> 33 ) 34 } 35 36 _onBtnPress(){ 37 alert('點我幹嘛?') 38 } 39 } 40 41 const styles=StyleSheet.create({ 42 btnStyle:{ 43 width:200, 44 height:40, 45 borderRadius:10, 46 backgroundColor:'red', 47 justifyContent:'center', 48 alignItems:'center' 49 } 50 })

2.App.js 引入自定義元件

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow strict-local
 */

import React from 'react';
import {
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  Text,
  StatusBar,
} from 'react-native';

import {
  Header,
  LearnMoreLinks,
  Colors,
  DebugInstructions,
  ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
import CKButton from './components/CKButton'

const App: () => React$Node = () => {

  return (
    <>
      <StatusBar barStyle="dark-content" />
      <SafeAreaView style={styles.mainViewStyle}>

      <CKButton/>
      </SafeAreaView>
    </>
  );
};


const styles=StyleSheet.create({
  mainViewStyle:{
      flex:1,
      backgroundColor:'#fff',
  }
});


export default App;

3.結果如圖