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

自定义View组件使用数字属性时TS报Object is possibly 'undefined'如何解决

问题原因
  1. 你定义的ViewContainerProps接口中,percentHeight、percentWidth均为带?的可选属性,TypeScript默认认为这类属性可能为undefined,直接参与数值运算就会触发Object is possibly 'undefined'报错。
  2. 代码中用到的onePercentHeight变量未在当前作用域定义,也会引发报错。
修复方案

根据你的使用场景可以任选以下方案:

  • 方案1:给可选属性设置默认值(最常用,不需要强制用户传参)
    解构props时直接指定默认值,保证参数一定是数字类型:
const {style, children, percentHeight = 100, percentWidth = 100} = props;
  • 方案2:运算时做兼容处理
    不需要修改接口和解构逻辑,在运算时用空值合并运算符兜底:
height: onePercentHeight * (percentHeight ?? 100)
  • 方案3:改为必传属性
    如果要求使用组件时必须传入百分比参数,直接去掉接口中属性后的?即可,TypeScript会强制校验调用方必须传值,不会再出现undefined的可能:
export interface ViewContainerProps {
  style?: ViewStyle | ViewStyle[];
  children?: React.ReactNode;
  percentWidth: number; // 去掉?
  percentHeight: number; // 去掉?
}

另外你需要先定义onePercentHeight变量,比如基于设备屏幕高度计算:

import { Dimensions } from 'react-native';
const onePercentHeight = Dimensions.get('window').height / 100;
完整修复示例代码
import { View, ViewStyle, Dimensions } from 'react-native';
import React from 'react';

const { height: windowHeight, width: windowWidth } = Dimensions.get('window');
const onePercentHeight = windowHeight / 100;
const onePercentWidth = windowWidth / 100;

export interface ViewContainerProps {
  style?: ViewStyle | ViewStyle[];
  children?: React.ReactNode;
  percentWidth?: number;
  percentHeight?: number;
}

export const ViewContainer = (props: ViewContainerProps) => {
  const {style, children, percentHeight = 100, percentWidth = 100} = props;
  return (
    <View style={[
      style, 
      {
        height: onePercentHeight * percentHeight,
        width: onePercentWidth * percentWidth
      }
    ]}>
      {children}
    </View>
  );
};

内容的提问来源于stack exchange,提问作者Lê Quốc Khánh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 09:57:00