天天看點

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)效果圖

  • 預設情況下點選大按鈕後會彈出消息提示框。
  • 點選下方的小按鈕可以交替切換大按鈕觸摸狀态 。如果目前大按鈕不處理觸摸事件,點選大按鈕則沒有反應。
React Native - pointerEvent屬性介紹(目前視圖是否處理觸摸事件)
React Native - pointerEvent屬性介紹(目前視圖是否處理觸摸事件)

(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

繼續閱讀