TouchableOpacity 透明觸摸
本組件用於封裝視圖,使其能夠正確響應觸摸操做。當按下的時候,封裝的視圖的不透明度會下降。react
不透明度的變化是經過把子元素封裝在一個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這個值git
/** * 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 : 點擊事件github
onPressIn: 是按下時的事件web
onPressOut:擡起事件react-native
onLongPress:長按事件
具體想要什麼事件,均可以本身去定義!
手機在操做過程當中不太好截圖,因此截了一張圖:svg
在使用react native中,還須要瞭解下生命週期問題,接下來將學習這個,一塊兒加油吧!佈局
本文同步分享在 博客「zoepriselife316」(CSDN)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。學習