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

解构组件传入的style对象时报错:Cannot read property 'fontSize' of undefined

解决解构嵌套styles时出现「Cannot read property 'fontSize' of undefined」的问题

问题场景回顾

你给Temp组件传入了styles对象:

<Temp styles={{fontWeight: 'bold', fontSize: '1.6'}} {...otherprops} />

但尝试用嵌套解构获取内部属性时:

{({styles: {fontSize, fontWeight}}) => /* 使用对应值 */ }

却触发了「Cannot read property 'fontSize' of undefined」错误,虽然后续打印styles能看到正确的值。

问题根源

这个报错的核心原因是:组件在初始渲染时,styles可能是undefined。

你看到打印的styles有值,大概率是组件后续更新(比如props传入完成)后的结果,但初始渲染阶段styles还没被赋值,这时候直接从undefined里解构fontSize和fontWeight,自然会抛出错误。

可行的解决办法

1. 给嵌套解构设置默认空对象

在解构时给styles兜底一个空对象,这样即使初始styles是undefined,也不会触发报错:

{({ styles: { fontSize, fontWeight } = {} }) => {
  // 这里fontSize和fontWeight初始时会是undefined,后续有值后会自动更新
  return <div style={{ fontSize, fontWeight }}>内容</div>;
}}

2. 先判断styles是否存在,再解构

先取出styles,确认它存在后再解构内部属性,这样更直观,也能灵活处理无值的情况:

{({ styles }) => {
  if (!styles) {
    // 可以返回加载状态或者空内容
    return <div>加载中...</div>;
  }
  const { fontSize, fontWeight } = styles;
  return <div style={{ fontSize, fontWeight }}>内容</div>;
}}

3. 使用可选链操作符(ES2020+)

如果你的项目支持ES2020及以上语法,可选链能让代码更简洁:

{({ styles }) => {
  const fontSize = styles?.fontSize;
  const fontWeight = styles?.fontWeight;
  return <div style={{ fontSize, fontWeight }}>内容</div>;
}}

可选链会在styles为undefined时直接返回undefined,不会触发报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:30:38