我正在运行 React Native 0.24.1,我遇到了 <TouchableOpacity>
的问题当组件放在 <ScrollView>
中时.
它的 onPress 事件可以正常触发,但在特殊情况下它们不会触发。
如果连同 <TouchableOpacity>
组件你有一个 <TextInput>
, 当前焦点在 <TextInput>
上框,然后您可以单击 <TouchableOpacity>
你会看到它的 onPress 事件不会被触发。
至少在您第一次这样做时。一旦焦点不在 <TextInput>
上现在,您可以按 <TouchableOpacity>
组件及其 onPress 事件将正常触发。
请注意,如果 <TouchableOpacity>
组件放置在 <View>
中而不是 <ScrollView>
一切都按预期工作,上述问题不适用。
下面是一些代码来演示这个问题:
const React = require('react-native');
const {
Component,
Dimensions,
View,
ScrollView,
Text,
TextInput,
TouchableOpacity,
} = React;
// ----------------------------------------------------------------------------
class TouchableOpacityTest extends Component {
constructor(props, context) {
super(props, context);
this.state = {count_onPress:0,count_onPressIn:0,count_onPressOut:0,count_onLongPress:0};
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
onPressEvent(what,e) {
console.log('what:',what);
let newState = {};
newState['count_'+what] = ++this.state['count_'+what];
this.setState(newState);
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
render() {
let touchableProps = {
onPress: this.onPressEvent.bind(this,'onPress'),
onPressIn: this.onPressEvent.bind(this,'onPressIn'),
onPressOut: this.onPressEvent.bind(this,'onPressOut'),
onLongPress: this.onPressEvent.bind(this,'onLongPress'),
}
return (
<View style={{flex:1,flexDirection:'column',justifyContent:'flex-start',alignItems:'center',backgroundColor:'blue'}} >
<ScrollView style={{width:Dimensions.get('window').width*0.9,backgroundColor:'red'}}>
<TextInput style={{backgroundColor:'rgb(200,200,200)',marginTop:14}}
placeholder="Focus on me,hide keyboard,and click on text below"
autoCorrect={false}
/>
<TouchableOpacity {...touchableProps} >
<Text style={{fontSize:20,backgroundColor:'pink',marginTop:14}}>
Click on me!{"\n"}
onPress:{this.state.count_onPress}{"\n"}
onPressIn:{this.state.count_onPressIn}{"\n"}
onPressOut:{this.state.count_onPressOut}{"\n"}
onLongPress:{this.state.count_onLongPress}{"\n"}
</Text>
</TouchableOpacity>
</ScrollView>
</View>
);
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
}
// ----------------------------------------------------------------------------
AppRegistry.registerComponent('react_native_app1', () => TouchableOpacityTest);
您可以替换 <ScrollView>
用<View>
上面代码中的组件,您会看到每次都会触发 onPress 事件,即使焦点位于 <TextView>
上也是如此。
注意:我在 Android 上工作。我不知道这是否也会发生在 iOS 上。
注意 2: 据 Aakash Sigdel 称,这确实也发生在 iOS 上。
最佳答案
在您的 ScrollView
上设置 keyboardShouldPersistTaps={true}
。
此处重复答案:https://stackoverflow.com/a/34290788/29493
更新:正如 Hossein 在他的回答中所写,true|false
在新版本中已被弃用,取而代之的是 always|never|handled
.
关于android - react native : TouchableOpacity onPress problems inside a ScrollView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36822391/