React Native的TouchableOpacity组件

TouchableOpacity 透明触摸
本组件用于封装视图,使其可以正确响应触摸操作。当按下的时候,封装的视图的不透明度会降低。

不透明度的变化是通过把子元素封装在一个Animated.View中来实现的,这个动画视图会被添加到视图层级中,少数情况下有可能会影响到布局。(译注:此组件与TouchableHighlight的区别在于并没有额外的颜色变化,更适于一般场景。)
使用之前,与Text,Image组件一样,都需要引入
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, Image, TextInput, TouchableOpacity } from 'react-native';
引入后,在文件中使用是这样的
activeOpacity={0.5} 是它点击时的颜色变化,0.8/0.9基本上看不出来,一般使用0.5这个值

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
  TextInput,
  TouchableOpacity
} from 'react-native';
var Dimensions = require ('Dimensions') ;
var {width,height} = Dimensions.get('window');
class Home extends Component {
  constructor(props) {
    super(props)
    this.state = { title:'默认文字' }
  }
  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity activeOpacity={0.5}
           onPress={()=>this.textPress('点击')}
           onPressIn={()=>this.textPress('按下时')}
           onPressOut={()=>this.textPress('按后')}
           onLongPress={()=>this.textPress('长按时...')}
         
           style={styles.textStyle}>
          <Text>我是文字。点击下看看吧</Text>
        </TouchableOpacity>
        <Text>{this.state.title}</Text>

      </View>
    );
  }

  textPress(value){
    // console.warn('点击成功')
    this.setState({
      title:value
    })
  }
}

const styles = StyleSheet.create({
  container:{
    flex: 1,
    alignItems:'center',
    justifyContent:'center',
    
  },
  textStyle:{
    backgroundColor:'red',
  },
});

module.exports = Home;

onPress : 点击事件

onPressIn: 是按下时的事件

onPressOut:抬起事件

onLongPress:长按事件
具体想要什么事件,都可以自己去定义!
手机在操作过程中不太好截图,所以截了一张图:

按下后显示的图片

在使用react native中,还需要了解下生命周期问题,接下来将学习这个,一起加油吧!

猜你喜欢

转载自blog.csdn.net/zoepriselife316/article/details/84344468