我正在運行反應原生0.24.1,並且當它被放置在<ScrollView>
中時,我遇到<TouchableOpacity>
組件的問題。React Native:TouchableOpacity onPress問題在滾動視圖
它的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);
您可以用<View>
部件更換<ScrollView>
在上面的代碼,每次你會看到,onPress事件觸發,即使當焦點是對<TextView>
注:我在Android上工作。我不知道這是否也發生在iOS上。
注2:根據Aakash Sigdel,這確實是發生在iOS上了。
嘗試使用其中一個keyboardDismissMode = {'none','ondrag','interactive'} – Mihir
我在iOS上檢查過它,並且可以確認這也發生在iOS中。 –
我有一個與ScrollView旁邊的類似的問題,但是在移除ScrollView時問題並未解決。相反,我將按鈕的大小增加到了最小推薦尺寸44x44。之後,該按鈕可識別所有輕擊事件。 –