我想过滤组件的键值。为此,我使用了filter。但是我得到了一个错误:TS2339: Property 'filter' does not exist on type 'string | number | boolean | {} | ReactElement<any> | ReactNodeArray | ReactPortal'. Property 'filter' does not exist on type 'string'.
键值是div的键值。
我尝试将其用作函数或常量,但仍收到相同的错误。
getComponent(key){
return this.props.children!.filter(component => {
return component.key === key;
});
}我希望过滤组件的键值。也许任何人都有同样的问题?
我正在使用React-typescript
发布于 2019-04-05 19:00:17
正如错误所述,为this.props.children列出的字符串、数字、布尔值和其他各种类型都没有名为filter的函数。因此,您需要首先确保处理的是一个数组,然后使用类型断言告诉TypeScript:
if (Array.isArray(this.props.children)) {
return (this.props.children as ReactNodeArray).filter(component => component.key === key);
}
// ...handle the fact it's not an array...发布于 2019-04-05 20:20:56
几周前我遇到过一个类似的问题,我使用React.Children迭代传递给组件的嵌套子对象。
下面是我编写的代码:
public renderByKey(childElement, key) {
return React.Children.map(childElement, child => {
if (child != null) {
if (child.props != undefined) {
if (typeof (child.type) !== 'string') {
if (child.props.key != undefined && child.props.key === key) {
return child;
}
}
if (child.props.children != undefined) {
return this.renderByKey(child.props.children,key);
}
}
}
});
}我知道递归带来的不便,但我将它与其他道具一起使用(而不是像你这样使用key ),并且对我来说很完美。
https://stackoverflow.com/questions/55533894
复制相似问题