How to open keyboard automatically in React Native?

后端 未结 4 1371
时光取名叫无心
时光取名叫无心 2020-12-17 10:51

I have a screen in my React Native application in which I have few text fields.

I was wondering if there is any way in which on screen load my keyword opens automati

相关标签:
4条回答
  • 2020-12-17 10:54

    The selected solution did not work for me due to stack navigation (see comment of "SoundStage" on selected solution)

    I added a new variable openTheKeyboard to the state initially set to false.

    My hacky solution:

    componentDidMount() {
      this.setState({ openTheKeyboard: true });
    }
    
    componentDidUpdate() {
      if (this.state.openTheKeyboard) {
        this.textInput.focus();
        this.setState({ openTheKeyboard: false });
      }
    }
    
    0 讨论(0)
  • 2020-12-17 11:08

    My way (there was a problem with focusing and showing a keyboard on component render)

    import { InteractionManager, TextInput } from 'react-native';
    
    ...
    
    inputRef = React.createRef();
    
    componentDidMount() {
      this.focusInputWithKeyboard()
    }
    
    focusInputWithKeyboard() {
      InteractionManager.runAfterInteractions(() => {
        this.inputRef.current.focus()
      });
    }
    
    render() {
      <TextInput ref={this.inputRef} />
    }
    
    0 讨论(0)
  • 2020-12-17 11:10

    This seems to be working in my simulator. Have not confirmed on a real device.

    constructor(props) {
      super(props);
      this.buildNameTextInput = React.createRef();
    }
    
    <TouchableOpacity
      style={styles.mainButton}
      onPress={() => {
        this.buildNameTextInput = true
        this.props.setSaveBuildModal(true)
      }}
    >
      <Text style={styles.mainButtonText}> Save Build </Text>
    </TouchableOpacity>
    
    <TextInput
      autoFocus={!!this.buildNameTextInput}
      ref={this.buildNameTextInput}
      placeholder="Type a Name"
      autoCapitalize="words"
      style={{...styles.heroBtnText, marginVertical: 50}}
      onChangeText={buildName => this.props.setCurrentBuildName(buildName)}
      value={this.props.buildName}
    />
    
    1. I needed the constructor to register the reference
    2. The handler sets a local variable to true
    3. autoFocus will trigger the field to be focused. The keyboard sometimes opens up on android simulator (this I cannot explain).
    4. ref is for the reference to the DOM element
    0 讨论(0)
  • 2020-12-17 11:12

    The keyboard should open automatically when a <TextField /> is focused. You can use the autoFocus prop to make it focus when the element mounts (link)

    0 讨论(0)
提交回复
热议问题