reactjs - 反应打字稿和孩子
问题描述
我尝试在打字稿中动态检查反应子组件的类型。以下代码运行良好,但似乎打字稿不希望我解构孩子。
我收到打字稿错误:
TS2339: Property 'type' does not exist on type 'ReactNode'.
我该怎么做才能摆脱打字稿错误而不是使用//@ts-ignore。
import * as React from 'react';
export interface AuxProps {
children: React.ReactNode[]
}
export const Message: React.FC<AuxProps> = ({
children,
}: AuxProps) => {
const test = children.filter(({ type }) => type === Test);
return (
<div>
{test}
<div/>
);
};
解决方案
你不能从 中读取type
,ReactChild
因为ReactChild
是一个联合,并且不是该联合的每个成员都有一个名为 的属性type
。
事实上,只有ReactElement
s 可以。
解决方案是检查谓词函数中的两件事:
- 这个孩子是
ReactElement
? - 如果是,那么该元素是所需类型的吗?
代码:
const test = children.filter(child => React.isValidElement(child) && child.type === 'Test');
推荐阅读
- python - Enumerating dataframe based on a column
- c# - 自动将 JSON 属性映射到 C# 属性
- javascript - 更改 SMTP 用户密码的自动化
- javascript - 如何从右到左匹配 React Router 路径
- string - 删除 nginx 配置变量上的前导零
- python-3.x - 从 pdf 文件中提取文本以使用 Gensim 构建模型
- jenkins - using Jenkins pipelines, call a parametrized job from another job
- build - Install gstreamer using cerbero
- parsing - parse(Float64,trip)--错误:无法将行程解析为 Float64
- matlab - matlab中具有叉积的复杂船体脚本