react-native - 如何在 React Native 中按下按钮打开键盘?

标签 react-native expo

我有一个按钮,当它被按下时,我希望它打开键盘并专注于文本输入组件。

对于一个最小的代码示例,我正在尝试做的是这个-

      <View>
          <AddSomething
            textChange={textInput => this.setState({ textInput })}
            addNewItem={this.addItem.bind(this)}
            textInput={this.state.textInput}
            ref={not sure what goes here} //passing these as props to a text input
          />
          <FloatingButton tapToAddHandler={this.onFloatingButtonPress.bind(this)} />
      </View>

然后是我处理按钮按下的一些辅助函数 (this.onFloatingButtonPress)

最佳答案

首先声明你的 AddSomething 如下:

const AddSomething = React.forwardRef((props, ref) => (
    <TextInput 
        ref={ref} 
        //your other code
    />
));

现在您可以使用 ref 并能够如下所示聚焦您的 AddSomething 组件:

      <View>
          <AddSomething
            textChange={textInput => this.setState({ textInput })}
            addNewItem={this.addItem.bind(this)}
            textInput={this.state.textInput}
            ref={(ref) => { this.textInputField = ref }}
          />
          <FloatingButton tapToAddHandler={this.onFloatingButtonPress.bind(this)} />
      </View>

这是您的onFloatingButtonPress 方法:

onFloatingButtonPress() {
    this.textInputField.focus();
} 

关于react-native - 如何在 React Native 中按下按钮打开键盘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58241596/

相关文章:

react-native - 如何在 React Native 中禁用键盘外观动画

javascript - React Native ListView 数据源始终为 null

react-native - 更新 React Native 后 React Native 版本不匹配

react-native - 无法使用 React Native 调试器进行调试

react-native - 为什么我在 React Native Expo 应用程序中尝试 Google Login 时会重定向到 "Google.com"?

ios - 不变违规 : Native component for "RNSVGSvgView" does not exist

reactjs - React Native - 导入整个文件/将 js 代码拆分到多个文件中

node.js - -bash : react-native: command not found

android - 新安装 Expo Go 的 Android 设备上 sdk 46.0.0 (@snack/sdk.46.0.0) 出现错误

react-native - 如何在 React Native Expo 应用程序中集成 i18n-js