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

React Native点击图标触发自定义TextInput调用blur失焦报错如何解决

问题原因
  1. React 函数组件默认不支持直接接收ref属性,你直接给自定义的TextInputCustom传的ref会被当做普通props处理,无法正常绑定到组件实例上
  2. 你需要调用的blur()是原生TextInput组件的方法,就算你拿到了外层自定义组件的实例,本身也没有blur方法
  3. 如果你的业务代码是函数组件,不存在this指向,用this.myInput存储ref本身就是错误写法
解决方案

第一步:修改自定义TextInputCustom组件,用forwardRef转发ref到内部原生TextInput

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

// 用forwardRef包裹组件,接收外部传入的ref
const TextInputCustom = forwardRef((props, ref) => {
  const {
    iconType,
    placeholder,
    onChange,
    onFocus,
    textContentType,
    autoCapitalize,
    autoCompleteType,
    iconPress,
  } = props;
  return (
    <View style={styles.inputView}>
      <Icon name={iconType} onPress={iconPress} size={20} />
      {/* 将外部传入的ref绑定到原生TextInput上 */}
      <TextInput
        ref={ref}
        style={{
          flex: 1,
          paddingHorizontal: 12,
        }}
        placeholder={placeholder}
        textContentType={textContentType}
        autoCapitalize={autoCapitalize}
        autoCompleteType={autoCompleteType}
        autoCorrect={false}
        onChangeText={(e) => onChange(e)}
        onFocus={onFocus}
      />
    </View>
  );
});

第二步:修改业务侧代码,正确使用ref

如果是函数组件,改用useRef存储ref:

import React, { useRef } from 'react';

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

// 渲染时绑定ref
<TextInputCustom
  ref={myInputRef}
  iconType={
    Platform.OS === "android" ? 
      isSearchbarFocused ? 'chevron-left' : 'search'
      : 'search'
  }
  iconPress={() => { 
    if(Platform.OS === "android" && isSearchbarFocused) {
      setSearchbarFocused(false);
      // 加可选链避免ref未绑定时报错
      myInputRef.current?.blur();
    } else {
      console.log("Hi");
    }
  }}
/>

如果是类组件,原有this.myInput的写法不用改,只需自定义组件完成上述forwardRef改造即可正常调用this.myInput.blur()。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 02:45:03