You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在点击按钮时移除React Native TextInput的焦点?

React Native点击按钮移除TextInput焦点的实现方案

完全可行,核心思路是通过给TextInput创建引用(ref),手动调用其blur()方法来移除焦点,具体实现步骤如下:

1. 创建TextInput的引用

在你的函数组件中,使用useRef钩子创建一个引用对象:

import { useRef } from 'react';
import { TextInput, View } from 'react-native';

// 组件内部定义ref
const inputRef = useRef(null);

2. 将引用绑定到TextInput组件

修改你现有的TextInput代码,添加ref属性绑定刚才创建的引用:

<TextInput
    ref={inputRef} // 绑定ref
    onChangeText={onChange}
    value={searchQuery}
    placeholder="Start typing to search or add your own"
    maxLength={80}
    onFocus={() => {
        setIsInputFocused(true);
    }}
    onBlur={() => {
        setIsInputFocused(false);
        setSearchQuery('');
    }}
    blurOnSubmit={true}
/>

3. 在可点击View的点击事件中调用blur方法

修改你的可点击View代码,在onPress回调里调用inputRef.current?.blur():

<View onPress={() => {
    // 安全移除输入框焦点
    inputRef.current?.blur();
}}></View>

补充说明

  • 使用?.可选链操作符是为了避免inputRef.current为null时出现报错,确保调用的安全性。
  • 如果你的组件是类组件,改用React.createRef()创建引用即可,调用方式类似:
class YourComponent extends React.Component {
    constructor(props) {
        super(props);
        this.inputRef = React.createRef();
    }

    render() {
        return (
            <>
                <TextInput ref={this.inputRef} {...你的其他属性} />
                <View onPress={() => this.inputRef.current?.blur()}></View>
            </>
        );
    }
}

内容的提问来源于stack exchange,提问作者Onyx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 16:18:34