当在 React 中尝试直接渲染一个普通 JavaScript 对象(如 { one: "...", two: "...", three: "..." })时,TypeScript 会报错 Type '...' is not assignable to type 'ReactNode',因为 React 无法自动将对象序列化为可渲染内容,必须显式提取并渲染其属性值。
当在 react 中尝试直接渲染一个普通 javascript 对象(如 `{ one: "...", two: "...", three: "..." }`)时,typescript 会报错 `type '...' is not assignable to type 'reactnode'`,因为 react 无法自动将对象序列化为可渲染内容,必须显式提取并渲染其属性值。
该错误源于 JSX 中对 feature 的直接插值:<span>{feature}</span>。React 要求所有插入到 JSX 中的表达式必须是合法的 ReactNode —— 即 null、undefined、字符串、数字、布尔值、React 元素(如 <div>)、数组或 Fragment,但不能是普通对象。而 feature 是一个具有 one、two、three 属性的对象字面量,TypeScript 严格校验后拒绝将其作为子节点传入。
正确做法是解构并分别渲染每个字段。以下是修复后的完整 pricingCard 实现:
const pricingCard = prices.map(({ name, price, features }) => ( <div key={name} className="p-6 border rounded-lg"> <h3 className="text-xl font-bold">{name}</h3> <p className="text-2xl mt-2">{price}</p> <ul className="mt-4 space-y-2"> {features.map((feature, idx) => ( <li key={idx} className="flex items-start space-x-3"> <svg className="flex-shrink-0 w-5 h-5 text-green-500 dark:text-green-400 mt-0.5" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg" > <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" /> </svg> <div> <p className="font-medium">{feature.one}</p> <p className="text-sm text-gray-600 dark:text-gray-400">{feature.two}</p> <p className="text-sm text-gray-600 dark:text-gray-400">{feature.three}</p> </div> </li> ))} </ul> </div>));
⚠️ 关键注意事项:
interface FeatureItem { one: string; two: string; three: string;}interface PricingPlan { name: string; price: string; features: FeatureItem[];}const prices: PricingPlan[] = [ /* ... */ ];
总结:React 渲染机制不支持隐式对象转字符串,所有嵌套数据必须显式解构并转化为合法 ReactNode。这是 TypeScript 类型系统对前端健壮性的有力保障,而非限制——它提前捕获了潜在的运行时错误(如 Cannot convert object to string),帮助你写出更可靠、易维护的组件逻辑。