React本机TextInput自动对焦不工作

xuo3flqw  于 2022-12-14  发布在  React
关注(0)|答案(3)|浏览(195)

我有两个屏幕在React原生应用程序说屏幕A屏幕B。一个文本输入是目前在屏幕A。我已经把自动对焦为真,它的工作最初。
当我们从屏幕A导航到屏幕B,然后从B-〉A导航回来时,textinput自动聚焦不起作用。
有没有人对此有什么想法??

  1. <TextInput
  2. style={styles.textInput}
  3. textStyle={styles.inputTextStyle}
  4. autoFocus={true}
  5. placeholder='Enter Code'
  6. keyboard={'numeric'}
  7. placeholderTextColor={AppStyles.color.grey}
  8. value={code}
  9. onChangeText={this.updateCode}
  10. underline={false}
  11. />
ngynwnxp

ngynwnxp1#

这是因为autofocus第一次在componentDidMount上触发。要在从B导航回A后手动触发它,您必须使用withNavigationFocus HOC。因此,当用户聚焦屏幕A时,您可以使用以下代码来显示键盘。

  1. import React from 'react';
  2. import { Text } from 'react-native';
  3. import { withNavigationFocus } from 'react-navigation';
  4. class FocusStateLabel extends React.Component {
  5. componentDidUpdate() {
  6. if(this.props.isFocused){
  7. this.inputField.focus();
  8. }
  9. }
  10. render() {
  11. return (
  12. <TextInput
  13. ref={(input) => { this.inputField = input; }}
  14. placeholder = "inputField"
  15. />
  16. )
  17. }
  18. }
  19. // withNavigationFocus returns a component that wraps FocusStateLabel and passes
  20. // in the navigation prop
  21. export default withNavigationFocus(FocusStateLabel);
展开查看全部
vfh0ocws

vfh0ocws2#

自动对焦 prop 只有在组件被挂载时才会触发。当你导航回A时,如果A仍然被挂载(只是隐藏),那么自动对焦将不会再次工作。
在从B导航回A时,应该使用ref(添加一个新状态,例如此处的ref)并添加一个处理程序来触发this.state.ref.focus()

  1. <TextInput
  2. ref={ref => ref && this.setState({ref})}
  3. style={styles.textInput}
  4. textStyle={styles.inputTextStyle}
  5. autoFocus={true}
  6. placeholder='Enter Code'
  7. keyboard={'numeric'}
  8. placeholderTextColor={AppStyles.color.grey}
  9. value={code}
  10. onChangeText={this.updateCode}
  11. underline={false}
  12. />
icomxhvb

icomxhvb3#

基于Jarret的注解(V6不赞成使用withNavigationFocus)和此StackOverflow答案(Can't focus TextInput when navigating to a screen):

  1. import {useFocusEffect} from 'react-navigation/native';
  2. const TestFocus = (props) => {
  3. const textRef = useRef(null);
  4. useFocusEffect(
  5. useCallback(() => {
  6. // When the screen is focused
  7. const focus = () => {
  8. setTimeout(() => {
  9. textRef?.current?.focus();
  10. }, 1);
  11. };
  12. focus();
  13. return focus; // cleanup
  14. }, []),
  15. );
  16. return (
  17. <TextInput
  18. ref={textRef}
  19. />
  20. )
  21. }
展开查看全部

相关问题