【REACT NATIVE 系列教程之二】創建自定義組件&&導入與使用示例
在上一篇 【REACT NATIVE 系列教程之一】觸摸事件的兩種形式與四種TOUCHABLE組件詳解 中的最后介紹了如何使用Touchable的四種組件進行監聽觸摸事件。
那么緊接著我們利用Touchable來包裝一個帶圖片的Button組件,且設計成可接受很多自定義參數。
一:創建我們自定義的Button,起名為MyButton, 且觸摸后的底色、觸發事件響應的函數、圖片資源、以及圖片大小都是根據傳過來的值確定的。
1.首先我們開始引入必要的一些組件
importReact, {
AppRegistry,
Component,
Image,
TouchableHighlight,
} from 'react-native';
2. 創建我們的MyButton組件,繼承 Component。
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中。
module.exports = MyButton;
二:使用自定義的MyButton
1. 導入我們的MyButton組件:
importMyButtonfrom './MyButton'
import X from ‘ Y ‘
X: 任意名字,用來代表我們導入的組件在此的臨時組件名(可以與原組件名一致)
Y: 組件所在的相對路徑
2. 在Render中使用:
<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中所用圖片的高
運行效果如下:(點擊查看動態圖)

來自: http://www.himigame.com/react-native/2219.html