打开模态时,如何将焦点设置在模态内的第一个 TouchableHighlight 组件(或另一个,例如由 ref 给出)上? [英] How can I set focus on the first TouchableHighlight component (or another one, given by ref for instance) inside the modal when modal is opened?
问题描述
如何在模态打开时将焦点设置到第一个(或任何给定的)TouchableHighlight 组件?我正在使用方向键/键盘/电视遥控器
How can I set focus to the first (or any given) TouchableHighlight component inside the modal when it's opened? I'm using D-pad/kayboard/TV Remote
让我们使用 react-native 文档模式示例的片段:
Let's use the fragment of the react-native documentation modal example:
<View style={{marginTop: 22}}>
<Modal
animationType="slide"
transparent={false}
visible={this.state.modalVisible}
onRequestClose={() => {
Alert.alert('Modal has been closed.');
}}>
<View style={{marginTop: 22}}>
<View>
<TouchableHighlight>
<Text>Button 1</Text>
</TouchableHighlight>
<TouchableHighlight>
<Text>Button 2</Text>
</TouchableHighlight>
<TouchableHighlight
onPress={() => {
this.setModalVisible(!this.state.modalVisible);
}}>
<Text>Hide Modal</Text>
</TouchableHighlight>
</View>
</View>
</Modal>
<TouchableHighlight
onPress={() => {
this.setModalVisible(true);
}}>
<Text>Show Modal</Text>
</TouchableHighlight>
</View>
使用方向键导航可以工作,但是当打开模态时,第一个 TouchableHighlight(按钮 1)没有聚焦,焦点仍然在显示模态"按钮上或者,如何以编程方式将焦点设置在Button 2"TouchableHighlight 上?
Navigation with D-pad works, but when the modal is opened, the first TouchableHighlight (button 1) is not focused, focus remains on the "Show Modal" button Or, How can I set focus on the "Button 2" TouchableHighlight programatically?
例如TextInput有自动对焦,但TouchableHighlight没有,如果我们在模态中只使用Touchable组件,我不知道如何自动对焦它们,或者隐式设置
TextInput for example has autoFocus, but TouchableHighlight no, if we are using only Touchable components inside a modal, I don;t know how to autoFocus them, or set implicitely it
最好的问候
推荐答案
将 hasTVPreferredFocus: true
添加到您想要聚焦的 TouchableHighlight.
Add hasTVPreferredFocus: true
to the TouchableHighlight you want focused.
它是在 Android 上实现的,尽管文档指出 hasTVPreferredFocus 仅适用于 iOS.
It is implemented on Android even though the documentation states that hasTVPreferredFocus is iOS-only.
以编程方式,您还可以通过调用强制聚焦:
Programmatically you can also force the focus by calling:
yourElementRef.setNativeProps({ hasTVPreferredFocus: true })
这篇关于打开模态时,如何将焦点设置在模态内的第一个 TouchableHighlight 组件(或另一个,例如由 ref 给出)上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!