【REACT NATIVE 系列教程之二】創建自定義組件&&導入與使用示例

本站文章均爲 李華明Himi 原創,轉載務必在明顯處註明: 
轉載自【黑米GameDev街區】 原文鏈接: http://www.himigame.com/react-native/2219.html


在上一篇  【REACT NATIVE 系列教程之一】觸摸事件的兩種形式與四種TOUCHABLE組件詳解 中的最後介紹瞭如何使用Touchable的四種組件進行監聽觸摸事件。

 那麼緊接着我們利用Touchable來包裝一個帶圖片的Button組件,且設計成可接受很多自定義參數。

一:創建我們自定義的Button,先創建一個js文件起名爲MyButton, 且觸摸後的底色、觸發事件響應的函數、圖片資源、以及圖片大小都是根據傳過來的值確定的。

1.首先我們開始引入必要的一些組件


1

2

3

4

5

6

import React, {

  AppRegistry,

  Component,

  Image,

  TouchableHighlight,

} from 'react-native';

 

2. 創建我們的MyButton組件,繼承 Component。


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

class MyButton extends Component {

render() {

return (

<TouchableHighlight  

                       underlayColor={this.props.bgColor}  

                       activeOpacity={0.5}

                       onPress={this.props.onPress}  

                 >  

    

<Image

                                source={require('./res/himi.png')}

style={ {

                                        width: this.props.imgWidth,

                                        height: this.props.imgHeight

                                 }}

                          />

                 </TouchableHighlight>

)

}

}

這裏需要注意的就一個  this.props: 

       在React中,組件的屬性可以在組件類的 this.props 對象上獲取。也就是說我們可以通過this.props對象上得到創建時傳過來的屬性。(注意屬性名字要保持一致,才能正確獲取到)

需要注意的:this.props.children 的值有三種可能:

a.如果當前組件沒有子節點,它就是 undefined ;

b.如果有一個子節點,數據類型是 object ;

c.如果有多個子節點,數據類型就是 array 。所以,處理 this.props.children 的時候要小心。

3. 將我們寫好的組件導入module中。


1

module.exports = MyButton;

 

二:使用自定義的MyButton  

1. 導入我們的MyButton組件:

 


1

import MyButton from './MyButton'

import X from ‘Y

X: 任意名字,用來代表我們導入的組件在此的臨時組件名(可以與原組件名一致)

Y: 組件所在的相對路徑

 

2.  在Render中使用:


1

2

3

4

5

6

7

<MyButton  

            bgColor='#000'

            onPress ={()=>{Alert.alert('Himi', ' MyBtton IS Click! ');}}

            imgWidth={100}

            imgHeight={100}

            >  

</MyButton>

bgColor: 傳給MyButton的按下後的底色

onPress: 傳給MyButton的觸發函數(這裏Himi偷懶用了lambda表達式)

imgWidth:傳給MyButton中所用圖片的寬

imgHeight:傳給MyButton中所用圖片的高

 

運行效果如下:(點擊查看動態圖)

user7

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章