React Native中TouchableOpacity致全屏可触摸,如何仅让按钮可点击?
解决TouchableOpacity导致整个屏幕可点击的问题
这个问题很常见,核心原因是你包裹TouchableOpacity的内层View没有任何样式约束,再加上外层slide3是flex:1占满全屏,导致TouchableOpacity的点击区域被意外拉伸到了整个屏幕。下面给你几个简单的修改方案:
方案1:给内层View添加样式,限制其仅包裹内容
只需要给包裹TouchableOpacity的那个<View>加上alignSelf: 'center'样式,让它只包裹按钮内容,而不是占满屏幕:
<View style={styles.slide3}> <Text>And simple</Text> <View style={{ alignSelf: 'center' }}> <TouchableOpacity onPress={() => this.handleStart(this.props.history)}> <Text>Start</Text> </TouchableOpacity> </View> </View>
方案2:移除多余的内层View,直接给TouchableOpacity加样式
其实那个内层View完全是多余的,直接给TouchableOpacity添加样式让它居中并仅包裹内容即可:
<View style={styles.slide3}> <Text>And simple</Text> <TouchableOpacity onPress={() => this.handleStart(this.props.history)} style={{ alignSelf: 'center' }} > <Text>Start</Text> </TouchableOpacity> </View>
额外优化:给按钮添加可视化样式(可选)
如果你想让按钮更直观,还可以给TouchableOpacity加内边距和背景色,既美化按钮,也能明确点击区域:
<View style={styles.slide3}> <Text>And simple</Text> <TouchableOpacity onPress={() => this.handleStart(this.props.history)} style={{ alignSelf: 'center', paddingVertical: 10, paddingHorizontal: 20, backgroundColor: '#4CAF50', borderRadius: 4 }} > <Text style={{ color: 'white' }}>Start</Text> </TouchableOpacity> </View>
补充说明
你注释掉的hitSlop属性是用来扩大点击区域的,如果你不需要扩大点击范围,保持注释状态就好,别打开它,否则会让点击区域比按钮本身更大。
内容的提问来源于stack exchange,提问作者Speedy11
相关产品推荐
相关产品推荐

