Demo展示
今天學(xué)的組件有點(diǎn)于類似于原生Android當(dāng)中的button则北,點(diǎn)擊它時它的背景會發(fā)生變化邢隧,給用戶一種視覺交互。在Android中叫selector,而在RN中叫Touchable系列瓷产。之前在學(xué)Text組件時站玄,我們通過onPress事件可以給Text組件綁定觸摸點(diǎn)擊事件。為了像Text組件那樣使得其他組件也可以被點(diǎn)擊濒旦,RN提供了三個Touchable類組件:
- TouchableHightlight:高亮觸摸株旷。用戶點(diǎn)擊時,會產(chǎn)生高亮效果
- TouchableOpacity:透明觸摸尔邓。用戶點(diǎn)擊時晾剖,被點(diǎn)擊的組件會出現(xiàn)透明效果
- TouchableWithoutFeedback:無反饋性觸摸。用戶點(diǎn)擊時梯嗽,被點(diǎn)擊的組件不會出現(xiàn)任何視覺變化齿尽。(沒有UI交互,一般很少用)
實(shí)現(xiàn)上圖效果
import React, {Component} from 'react';
import {
AppRegistry,
StyleSheet,
Text,
TouchableHighlight,
TouchableOpacity,
View
} from 'react-native';
class RNStudyFour extends Component {
show(text) {
alert(text);
}
render() {
return (
<View >
<TouchableHighlight
style={styles.container}
onPress={this.show.bind(this, 'TouchableHighlight activeOpacity')}
activeOpacity={0}
underlayColor="#00FF00">
<View >
<Text style={styles.font}>TouchableHighlight</Text>
<Text style={styles.font}>activeOpacity</Text>
</View>
</TouchableHighlight>
<TouchableHighlight
style={styles.container}
onPress={this.show.bind(this, 'TouchableHighlight underlayColor')}
underlayColor="#00FF00">
<View >
<Text style={styles.font}>TouchableHighlight</Text>
<Text style={styles.font}>underlayColor</Text>
</View>
</TouchableHighlight>
<TouchableOpacity
style={styles.container}
onPress={this.show.bind(this, 'TouchableOpacity')}>
<Text style={styles.font}>TouchableOpacity</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
height: 100,
backgroundColor: '#FF0000',
borderRadius: 10,
justifyContent: 'center',
alignItems: 'center',
marginLeft: 30,
marginRight: 30,
marginTop: 30
},
font: {
fontSize: 25,
color: '#fff'
},
});
AppRegistry.registerComponent('RNStudyFour', () => RNStudyFour);
實(shí)現(xiàn)起來還是比較簡單的灯节。有兩個地方需要注意一下:
-
TouchableHighlight的activeOpacity和underlayColor
- activeOpacity:觸摸時透明度的設(shè)置
- underlayColor:點(diǎn)擊時背景陰影效果的背景顏色
TouchableHighlight還有兩個屬性循头,我們大部是用這兩個,其它的就不介紹了显晶。它們之間的區(qū)別根據(jù)圖中可以明顯的看出來贷岸。因?yàn)榈谝粋€按鈕設(shè)置的activeOpacity為0,所以點(diǎn)擊第一個按鈕后完全不透明。
- TouchableOpacity也有activeOpacity屬性磷雇,但我們經(jīng)常不用它,因?yàn)槟J(rèn)就設(shè)置背景顏色的變化了躏救。
好了唯笙。今天的Touchable系列組件就學(xué)完了。若有不對之處盒使,還請告知崩掘。謝謝!