React Native - pointerEvent属性介绍(当前视图是否处理触摸事件)
http://www.hangge.com/blog/cache/detail_1748.html
在 React Native 开发时,很多组件都被布局在手机屏幕上,其中有一些组件使用绝对定位布局,即这些组件可能会遮盖住它们位置下方的某个组件的部分或者全部。
在 React Native 框架中,触摸事件总是被传送给最上层的组件。但有时候我们又需要被遮盖住的组件能够处理触摸事件。
比如:我们在一个地图组件上覆盖一个图像组件用来显示信息,但又不想让这个图像组件影响用户手指拖动地图的操作。这时我们就需要使用图像组件从 View 组件继承得到的 pointerEvents 属性来解决这个问题。
1,pointerEvent属性
pointerEvent 属性用于控制当前视图是否可以作为触控事件的目标。该属性是字符串类型的属性,有如下几种取值:
- none:发生在本组件与本组件的子组件上的触摸事件都会交给本组件的父组件处理。
- box-none:发生在本组件显示范围内(但不是子组件显示范围内)的事件交给本组件,在子组件显示范围内交给子组件处理。
- box-only:发生在本组件显示范围内的触摸事件将全部由本组件处理(即使触摸事件发生在本组件的子组件显示范围内)。
- auto:视组件的不同而不同。
注意:并不是所有的子组件都支持 box-none 和 box-only 两个值,我们使用时最好测试下。
2,使用样例
(1)效果图
- 默认情况下点击大按钮后会弹出消息提示框。
- 点击下方的小按钮可以交替切换大按钮触摸状态 。如果当前大按钮不处理触摸事件,点击大按钮则没有反应。
(2)样例代码
注意:由于 Android 系统下,直接在 Text 组件上设置 pointerEvents 没有效果。所以这里在大按钮外部有包了层 View 组件,并设置这个 View 组件的 pointerEvents 属性。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
import
React, { Component } from 'react' ;
import
{
AppRegistry,
StyleSheet,
View,
Text,
}
from 'react-native' ;
class
Main extends Component {
constructor(props)
{
super (props);
this .state
= {
bigButtonPointerEvents: null , //状态机变量控制大按钮是否工作
};
}
onBigButtonPressed()
{
alert( "大按钮点击" );
console.log( '大按钮点击' );
}
onSmallButtonPressed()
{
if ( this .state.bigButtonPointerEvents
=== null )
{
console.log( '让大按钮不处理触摸事件。' );
this .setState({bigButtonPointerEvents: 'none' }); //改变状态机变量
return ;
}
console.log( '让大按钮正常工作。' );
this .setState({bigButtonPointerEvents: null }); //改变状态机变量
}
render()
{
return (
<View
style={styles.container}
pointerEvents= 'box-none' >
<View
pointerEvents={ this .state.bigButtonPointerEvents}>
<Text
style={styles.bigButton}
onPress={ this .onBigButtonPressed.bind( this )}>
大按钮
</Text>
</View>
<Text
style={styles.smallButton}
onPress={ this .onSmallButtonPressed.bind( this )}>
{ this .state.bigButtonPointerEvents
=== null ? "当前大按钮正常工作" : "当前大按钮不处理触摸事件" }
</Text>
</View>
);
}
}
const
styles = StyleSheet.create({
container:
{ //根View样式
flex:
1,
alignItems: 'center' ,
marginTop:
10
},
bigButton:
{ //大按钮的样式
width:
200,
height:
70,
fontSize:
20,
textAlign: 'center' ,
textAlignVertical: 'center' ,
color: 'white' ,
backgroundColor: 'orange' ,
},
smallButton:
{ //
小按钮的样式
width:
200,
height:
35,
textAlign: 'center' ,
textAlignVertical: 'center' ,
color: 'white' ,
backgroundColor: 'grey'
},
});
AppRegistry.registerComponent( 'HelloWorld' ,
() => Main);
|
原文出自:www.hangge.com 转载请保留原文链接:http://www.hangge.com/blog/cache/detail_1748.html