Stacked TouchableOpacity inside another TouchableOpacity is not clickable

别等时光非礼了梦想. 提交于 2020-07-17 06:18:05

问题


Even though this document (https://facebook.github.io/react-native/docs/gesture-responder-system.html) states, that touch events are passed down to the children and are only consumed by a parent, if the child doesn't react on the event, I face the issue, that a TouchableOpacity nested inside another TouchableOpacity doesn't react properly on touches.

My structure is like follows

<ScrollView>
  <TouchableOpacity onPress={() => console.log('This is printed always')}>
    <View>
      <Text>I can click here</Text>
      <TouchableOpacity onPress={() => console.log('This is printed never')}>
        <Text>I can click here but the outer onPress is called instead of the inner one</text>
      </TouchableOpacity>
    </View>
  </TouchableOpacity>
</ScrollView>

The same happens for Buttons inside TouchableOpacitys: Clicking the Buttons calls the onPress method of the parent TouchableOpacity

Am I overseeing something?


回答1:


Change import of Touchable opacity from

import { TouchableOpacity } from 'react-native-gesture-handler';

To the following and it will now all be fine!

import { TouchableOpacity } from 'react-native';



回答2:


Writing here to make it a little more prominent.

It could be the nested TouchableOpacity is being imported from something different from the parent one as mentioned by @EliezerSteinbock. This could be quite possible as many of us use auto-imports on visual code or other IDE.

Sadly I missed her comment the first time round, so hopefully this would help someone else




回答3:


You could just use TouchableWithoutFeedback to wrap inner TouchableOpacity.

Something like:

<TouchableOpacity onPress={() => console.log('This is printed always')}>
    <View>
        <Text>I can click here</Text>
        <TouchableWithoutFeedback>
            <TouchableOpacity onPress={() => console.log('This is printed never')}>
                <Text>I can click here but the outer onPress is called instead of the inner one</text>
            </TouchableOpacity>
        </TouchableWithoutFeedback>
    </View>
</TouchableOpacity>


来源:https://stackoverflow.com/questions/44593024/stacked-touchableopacity-inside-another-touchableopacity-is-not-clickable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!