React native自定義元件之Button按鈕
最近也是在自學react native這一塊,其中也踩了不少坑,由於使用windows環境,可能是因為運氣不好,最開始配環境的時候就出現了很多問題,當成功之後也發現,啊哈,原來如此,有一朋友就很順利一遍就成功。好了還是進入主題,在Android原生開發中我們大多都會事先在drawable中定製幾個按鈕然後在專案中直接呼叫很方便。當然,在react native開發中我們也可以事先寫好一個button,然後在import進來直接使用。接下來我把主要步驟記錄下來,方便以後檢視,也可以給初學者做做參考,謝謝。
1,第一步先在專案中新建button.js檔案,button中的程式碼如下:
import React, { Component } from 'react';
import {
View,
Text,
Dimensions
} from 'react-native';
import { flextCenter } from './values/style'
export default class Button extends Component {
render(){
return(
<View style = {{...flextCenter,backgroundColor:'blue',width:Dimensions.get('window' ).width-40,height:45}}>
<Text style = {{color:'white',fontSize:20}}>登入</Text>
</View>
);
其中 class Button 元件一定要匯出去也就是使用export default 關鍵字,這樣外面才可以引用,至於程式碼中的…flextCenter的使用是這麼來的,我事先建了style.js檔案,然後檔案中聲明瞭flextCenter變數程式碼如下:
export const flextCenter={justifyContent:'center' ,alignItems:'center'}
其中也使用了export class關鍵字,這樣在button.js檔案中匯入flextCenter就可以直接使用了,匯入程式碼如下
import { flextCenter } from './values/style'
由於flextCenter是一個變數所以用了{},這樣在元件中就直接可以使用該屬性了,至於這兩個屬性的作用我就不多提了。當然,如果使用的屬性更多,你還可以在該變數中加入其他屬性比如backgroundColor都是可以的。
然後就是在其他元件中使用Button元件了,這裡我新建了find.js檔案,檔案中的程式碼如下:
import React,{Component} from 'react';
import {
View,
StyleSheet
} from 'react-native';
import Button from './button'
export default class Find extends Component{
render(){
return(
<View style = {styles.container}>
<Button/>
</View>
);
}
}
const styles = StyleSheet.create({
container:{
flex:1,
justifyContent:'center',
alignItems:'center',
},
})
為了方便我是在index.android.js中註冊的Find,程式碼如下:
import React, { Component } from 'react';
import {
AppRegistry,
} from 'react-native';
import Find from './app/find'
AppRegistry.registerComponent('MyScreen', () => Find);
最後實現的效果圖如下:
其實我們在原生開發中大多按鈕都是帶有圓角的,我們只需要在元件Button中給View多增加一些樣式就可以實現,增加程式碼如下
borderRadius:20
然後效果圖:
至此其實自定義元件Button已經可以使用了,其實還有很多不足,比如,寬度高度都是我們事先寫死了,也就是固定的,這樣使用起來也很不方便,接下來我們修改button.js中的程式碼,然後可以讓使用者自定義寬高以及背景顏色還有文字:
render(){
const {width,height,backgroundColor,children,borderRadius} = this.props
return(
<View style = {{...flextCenter,backgroundColor,width,height,borderRadius}}>
<Text style = {{color:'white',fontSize:20}}>{children}</Text>
</View>
);
}
引用元件部分程式碼:
render(){
return(
<View style = {styles.container}>
<Button backgroundColor = {'blue'}
width = {Dimensions.get('window').width - 40}
height = { 45 }
borderRadius = { 20 }>
這是自定義元件
</Button>
</View>
);
}
效果圖:
現在該元件稍加修改已經可以滿足大部分需求了,由於我也是學習這塊沒多久不足之處還請多多見諒。
最後我自己也在用React native 寫了一個小專案,也是抽時間再寫,完成了登入註冊模組,然後導航欄也加進去了,我會抽時間把這個專案逐漸完善,最後也是附上專案地址,希望大家多多指教。謝謝。