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

给React组件添加forwardRef时报TypeError: Component is not a function如何解决

问题修复方案

你遇到的TypeError: Component is not a function报错可以通过以下几个修改点解决:

  • 修正类型拼写错误:代码中泛型参数的ICustomtextnputProps拼写错误,需替换为你实际定义的自定义输入框属性类型(正确拼写通常为ICustomTextInputProps),拼写错误会导致编译产物异常。
  • 显式传递ref到内部Input组件:你当前没有将forwardRef拿到的ref传递给内层react-native-elements的Input组件,调整代码如下:
import React from 'react';
import { forwardRef } from 'react';
import { TextInput, TextInputFocusEventData, NativeSyntheticEvent, StyleSheet } from 'react-native';
import { Input, InputProps } from 'react-native-elements';
import { Metrics, Colors } from '../../theme';
import Icons from '../Icons';

// 首先确保你的ICustomTextInputProps已经正确定义,且拼写正确
interface ICustomTextInputProps extends InputProps {
  name?: string;
  required?: boolean;
  // 其他自定义属性
}

const CustomTextInput2 = forwardRef<TextInput, ICustomTextInputProps>((props, ref) => {
    const { name, required, ...rest } = props;

    return (
        <Input
            ref={ref} // 新增ref传递
            rightIcon={<Icons name="right" />}
            placeholder={name?.concat(required ? '*' : '')}
            inputContainerStyle={styles.inputContainer}
            inputStyle={styles.inputText}
            {...rest}
        />
    )
});

// 导出时注意和导入方式匹配
export default CustomTextInput2;
  • 检查导出导入匹配:
    • 如果用export default CustomTextInput2导出,导入语法为import CustomTextInput2 from './组件文件路径',不要加花括号
    • 如果用export const CustomTextInput2 = xxx导出,导入语法为import { CustomTextInput2 } from './组件文件路径',必须加花括号
      导出导入不匹配会导致拿到的组件值为undefined,渲染时就会触发不是函数的报错。
  • 确认TextInput类型已正确导入:forwardRef的第一个泛型参数用到的TextInput需要从react-native包中导入,避免类型缺失导致编译问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 06:15:04