【问题标题】:Property 'filter' does not exist on type 'string'“字符串”类型上不存在属性“过滤器”
【发布时间】:2019-08-27 06:27:47
【问题描述】:
我想过滤组件键值。我为此使用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
【问题讨论】:
标签:
reactjs
typescript
filter
【解决方案1】:
正如错误所说,为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...
【解决方案2】:
几周前我遇到了类似的问题,我使用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),并且非常适合我。