React Native 系統庫中只提供了IOS的實現,即ActionSheetIOS.該控件的顯示方式有兩種實現:
(1)showActionSheetWithOptions
(2)showShareActionSheetWithOptions
第一種是在iOS設備上顯示一個ActionSheet彈出框。第二種實現是在iOS設備上顯示一個分享彈出框。借用官方的圖片說明如下:
IOS設備上的實現系統已經提供了,接下來我們就需要如何適配Android。在原生開發(fā)中,自定義View也是有基本的流程:
(1)自定義控件類,繼承View或系統控件。
(2)自定義屬性
(3)獲取自定義屬性,并初始化一系列工具類
(4)重寫onMeasure方法,對控件進行測量
(5)如果是自定義布局,還需要重寫onLayout進行布局
在React Native中自定義組件的思路基本和原生自定義相似。所以按照這個流程,我們一步步實現即可。
二、功能實現
1、自定義組件,實現Component
export default class AndroidActionSheet extends Component
2、自定義屬性
// 1.聲明所需要的屬性 static propTypes= { title: React.PropTypes.string, // 標題 content: React.PropTypes.object, // 內容 show: React.PropTypes.func, // 顯示 hide: React.PropTypes.func, // 隱藏 }
constructor(props) { super(props); this.translateY = 150; this.state = { visible: false, sheetAnim: new Animated.Value(this.translateY) } this.cancel = this.cancel.bind(this); }
3、實現基本布局
render() { const { visible, sheetAnim } = this.state; return( <Modal visible={ visible } transparent={ true } animationType="none" onRequestClose={ this.cancel } > <View style={ styles.wrapper }> <TouchableOpacity style={styles.overlay} onPress={this.cancel}></TouchableOpacity> <Animated.View style={[styles.bd, {height: this.translateY, transform: [{translateY: sheetAnim}]}]}> { this._renderTitle() } <ScrollView horizontal={ true } showsHorizontalScrollIndicator={ false }> {this._renderContainer()} </ScrollView> </Animated.View> </View> </Modal> ) }
可以看到上面我們定義了基本的布局,布局中使用_renderTitle()方法來渲染標題部分,內容區(qū)域為ScrollView,并且為橫向滾動,即當菜單項超過屏幕寬度時,可以橫向滑動選擇。在內部調用了renderContainer方法來渲染菜單:
_renderTitle() { const { title,titleStyle } = this.props; if (!title) { return null } // 確定傳入的是不是一個React Element,防止渲染的時候出錯 if (React.isValidElement(title)) { return ( <View style={styles.title}>{title}</View> ) } return ( <Text style={[styles.titleText,titleStyle]}>{title}</Text> ) } _renderContainer() { const { content } = this.props; return ( <View style={styles.container}> { content } </View> ) }
當我們需要點擊Modal,進行關閉時,還需要處理關閉操作,Modal并沒有為我們提供外部關閉處理,所以需要我們單獨實現,從布局代碼中我們看到TouchableOpacity作為遮罩層,并添加了單機事件,調用cancel來處理:
cancel() { this.hide(); }
4、自定義方法,對外調用
在外部我們需要控制控件的顯示和隱藏,所以需要對外公開顯示、關閉的方法:
show() { this.setState({visible: true}) Animated.timing(this.state.sheetAnim, { toValue: 0, duration: 250 }).start(); }
hide() { this.setState({ visible: false }) Animated.timing(this.state.sheetAnim, { toValue: this.translateY, duration: 150 }).start(); }
5、使用
<ActionSheet ref='sheet' title='分享' content={this._renderContent()} />
至此,我們自定義組件就完成了。整體來看,基本的原理還是很簡單的,主要利用了自定義屬性,傳參,動畫,就可以輕松的實現了。本篇博客重點不是為了讓大家知道怎么去寫出這個效果,而是讓大家明白,當我們遇到一個需要自定義的實現時,該如何去一步步實現。
三、效果圖
相關推薦:
React Native自定義組件實現抽屜菜單控件效果
微信小程序開發(fā)之抽屜菜單實例詳解
用CSS打造 抽屜菜單_經驗交流
以上就是React Native自定義控件實現底部抽屜菜單的詳細內容,更多請關注php中文網其它相關文章!