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

如何从ReactNode类型数组中获取组件的props?

从ReactNode类型数组中获取组件props的解决方案

问题场景

你定义了包含ReactNode类型的数组:

let data: {title: ReactNode}[] = [
   {title: "test1"}, 
   {title: <Component1 title="test2" />},
   {title: "200"},
   {title: <Component2 title="test3" />}
 ]

编写getTitle方法时,尝试访问item.title.props出现TypeScript错误:

Property 'props' does not exist on type 'ReactElement<any, string | JSXElementConstructor<any>> | ReactFragment | ReactPortal'.
Property 'props' does not exist on type 'ReactFragment'.ts(2339)

解决方案

可以获取组件的props,但需要先做精确的类型收窄。ReactNode是联合类型,包含字符串、数字、ReactElement、Fragment、Portal等,只有ReactElement类型拥有props属性。

修改后的代码示例

import React from 'react';

let result: Record<number, string> = {};

const getTitle = () => {
  data.forEach((item, index) => {
    // 处理字符串/数字类型的title
    if (typeof item.title === 'string' || typeof item.title === 'number') {
      result[index] = item.title.toString();
    } 
    // 处理ReactElement类型的title,安全访问props
    else if (React.isValidElement(item.title)) {
      result[index] = item.title.props.title;
    }
    // 其他ReactNode类型(如Fragment、Portal)可按需补充处理逻辑
  });
};

关键说明

  • 使用React.isValidElement()做类型判断:这是React官方提供的方法,能准确识别React元素,同时TypeScript会自动将item.title的类型收窄为ReactElement,消除类型报错。
  • 避免直接用typeof 'object'判断:Fragment、null等也是object类型,但它们没有props属性,会导致类型不安全。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 21:15:36