在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;

效果:

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐