首页 > 解决方案 > React.Children.toArray 找不到使用打字稿的孩子的道具

问题描述

Typescript 无法使用 React.Children.toArray 检测子级的道具对象,我必须使用 any[] 因为如果我使用 ReactChild[] - 在数组项上未检测到道具。如何正确输入?谢谢!

const items: any[] = React.Children.toArray(this.props.children)

// select whatever item was told to be onload first
const itemPaymentType = items[0].props['data-payment']

在此处输入图像描述

标签: reactjstypescript

解决方案


卡西伯的答案是正确的。

但为了使用打字稿访问您的道具,需要这样做:

const item = items[0];
if (React.isValidElement<{prop1: boolean}>(item)) {

    // item.props.prop1 -- works
}

推荐阅读