react-native系列(8)組件篇:Touchable實現按鈕的點擊觸摸效果

在RN中並沒有onclick監聽,想要在組件中註冊點擊事件,需要使用Touchable。該組件也可以理解爲一個Animated.View容器,然後把需要註冊點擊事件的組件作爲子組件,並註冊onPress函數實現點擊效果。

Touchable目前有三種效果:

  1. TouchableHighlight:點擊時顯示高亮效果
  2. TouchableOpacity:點擊時顯示半透明效果
  3. TouchableWithoutFeedback:無效果

Touchable屬性:

屬性 描述

style

顯示樣式

onPress

註冊點擊(觸摸)事件函數

onPressIn

按下時觸發的函數

onPressOut

鬆開時觸發的函數

onLongPress

長按時觸發的函數

delayLongPress

設置觸發onLongPress事件所需要的長按時間,單位毫秒

activeOpacity

範圍0~1,表示觸摸時顯示的透明度,TouchableHighlight默認爲0.85;TouchableOpacity默認爲0.2

underlayColor

僅TouchableHighlight有效,表示觸摸操作時組件的背景色

貼上代碼:

import React, { Component } from 'react';
import { 
    View, 
    StyleSheet, 
    Text, 
    TouchableHighlight, 
    TouchableOpacity 
} from 'react-native';

class TouchableComp extends Component {

    _onPress = () => {
        console.log('onPress');
    }

    _onPressOut = () => {
        console.log('onPressOut');
    }

    _onPressIn = () => {
        console.log('onPressIn');
    }

    _onLongPress = () => {
        console.log('onLongPress');
    }

    render() {
        return (
            <View>
                <TouchableHighlight
                    style={styles.buttonStyle}
                    onPress={this._onPress}
                    onPressIn={this._onPressIn}
                    onPressOut={this._onPressOut}
                    onLongPress={this._onLongPress}
                    activeOpacity={0.85}
                    delayLongPress={3800}
                    underlayColor='green'
                >
                    <Text style={styles.textStyle}>TouchableHighlight</Text>
                </TouchableHighlight>

                <TouchableOpacity
                    style={styles.buttonStyle}
                    onPress={this._onPress}
                    onPressIn={this._onPressIn}
                    onPressOut={this._onPressOut}
                    onLongPress={this._onLongPress}
                    delayLongPress={3800}
                    activeOpacity={0.2}
                >
                    <Text style={styles.textStyle}>TouchableOpacity</Text>
                </TouchableOpacity>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    buttonStyle:{
        justifyContent: 'center',
        borderColor: '#000000',
        backgroundColor: '#DDDDDD',
        borderWidth: 1,
        borderRadius: 10,
        margin: 20,
        height: 50
    },
    textStyle:{
        fontSize: 16,
        color: '#000000',
        alignSelf: 'center'
    }
});

export default TouchableComp;

效果:

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