首页 > 解决方案 > 如何在自定义 react-native TextInput 中实现焦点/模糊响应

问题描述

我实现了一个由本地库支持的自定义react-native TextInput。它工作得很好,只是当我在文本字段之外点击时,它不会自动模糊并且键盘也不会消失。我也试过了Keyboard.dismiss(),它也不起作用。我查看了“官方”TextInput实现来复制它,但没有成功。

我在我的自定义实现中添加了这段代码(componentDidMount

    if (this.context.focusEmitter) {
      this._focusSubscription = this.context.focusEmitter.addListener(
        'focus',
        el => {
          if (this === el) {
            this.requestAnimationFrame(this.focus);
          } else if (this.isFocused()) {
            this.blur();
          }
        },
      );
      if (this.props.autoFocus) {
        this.context.onFocusRequested(this);
      }
    } else {
      if (this.props.autoFocus) {
        this.requestAnimationFrame(this.focus);
      }
    }

我还定义了所需的 contextTypes

    static contextTypes = {
      focusEmitter: PropTypes.instanceOf(EventEmitter)
    }

来自 TextInput 的代码

我遇到的问题focusEmitter是在上下文中是未定义的,我不知道它是从哪里提供的,也不知道它是否真的适用于常规的TextInput. focusEmitter我可以在 react-native 存储库中找到的唯一出现是在 NavigatorIOS 中,我什至没有在我的应用程序中使用它。谁能向我澄清这一点?

标签: react-nativetextfield

解决方案


做你想做的事情的更简单的方法是Keyboard.dismiss()TouchableWithoutFeedback下面的例子中使用:

import {Keyboard} from 'react-native';
...
render(){
  return(
    <TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
      <View>
        // Return everything here
        <TextInput />
      </View>
    </TouchableWithoutFeedback>
  )
}

因此,当您在输入之外点击时,它将关闭键盘并模糊TextInput.


推荐阅读