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

React Native Fabric组件使用Enum/Type遇codegen错误求助

React Native Fabric 原生组件:联合类型Props的Codegen问题解决

你完全可以用这类字符串联合类型("s" | "m" | "l")作为Fabric组件的props字段,报错「A default enum value is required for "size"」是因为Codegen对枚举/联合类型的props有两个硬性要求,满足其中一个就能解决:

解决方法1:给size字段设置默认值

如果size是必填项,就在组件定义时指定默认值,让原生端有明确的 fallback 值:

type SizeType = "s" | "m" | "l";

interface NativeProps extends ViewProps {
  size: SizeType;
}

const MyComponent = codegenNativeComponent<NativeProps>('MyComponent', {
  defaultProps: {
    size: "m" // 设置默认值,比如选中间的"m"
  }
});

解决方法2:标记size为可选字段(如果允许不传递)

如果你的组件允许不传入size,把字段改成可选类型即可,也可以同时搭配默认值:

type SizeType = "s" | "m" | "l";

interface NativeProps extends ViewProps {
  size?: SizeType; // 加问号标记为可选
}

// 可选字段也可以加默认值,或者按需省略
const MyComponent = codegenNativeComponent<NativeProps>('MyComponent', {
  defaultProps: {
    size: "m"
  }
});

为什么会报错?

Fabric的Codegen需要确保原生端处理props时不会出现未定义的状态,对于枚举/联合类型这类有固定取值范围的props,必须明确告诉Codegen:当JS端没传这个值时,原生该用什么默认值,或者这个值是可选的(允许未传递)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 10:24:53