在父响应者和子响应者中对e.nativeEvent点进行本地反应

时间:2019-03-22 13:58:50

标签: react-native

代码

class Demo extends React.Component {
  render(){
    return (
      <View
        onStartShouldSetResponder={(e)=>{
          console.log('parent line',e.nativeEvent.locationX)
          return true
        }}
        style={{width:300,height:20,backgroundColor:'green'}}
      >
         <View 
           onStartShouldSetResponder={(e)=>{
             console.log('child point',e.nativeEvent.locationX)
             return false//make the parent can also respond to the touch event
           }}

           style={{marginLeft:50,width:20,height:20,borderRadius:10,backgroundColor:'white'}}
         />
      </View>
    )
  }
}

概述

touch parent line view

touch child point view

如果我只触摸Parent Line View,则onStartShouldSetResponder event.nativeEvent.locationX确实是我触摸位置的地方。也许是299或0

如果我触摸Child Point View,并操纵Child Point ViewParent Line View的{​​{1}},它们是相同的,但它们都基于nativeEvent.locationX区域。

让我换一种说法,结果必须小于50,并且必须小于20,显然不是我想要的Child Point View locationX

为什么

1 个答案:

答案 0 :(得分:0)

该演示可以清楚地解释这个问题

class Demo extends React.Component {
  state={
    left:0
  }

  render(){
    return (
      <View style={{flex:1,justifyContent:'center'}}>
                <View
                    onStartShouldSetResponder={(e)=>{
                        console.log('parent line',e.nativeEvent.locationX,e)
                        this.setState({left:e.nativeEvent.locationX})
                        return true
                    }}
                    onResponderMove={(e)=>{
                        console.log('move',e.nativeEvent)
                        this.setState({left:e.nativeEvent.locationX})
                    }}
                    style={{width:'100%',height:20,justifyContent:'center',backgroundColor:'green'}}
                >
                    <View
                        onStartShouldSetResponder={(e)=>{
                            console.log('child point',e.nativeEvent.locationX,e)
                            return false
                        }}
                        onMoveShouldSetResponder={(e)=>{
                            return false
                        }}
                        style={{position:'absolute',left:this.state.left,height:20,width:20,borderRadius:10,backgroundColor:'#fff'}}
                    />

                </View>
            </View>
    )
  }
}

Demo Preview gif