首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >类型'string‘上不存在属性'filter’

类型'string‘上不存在属性'filter’
EN

Stack Overflow用户
提问于 2019-04-05 18:56:47
回答 2查看 1.7K关注 0票数 0

我想过滤组件的键值。为此,我使用了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的键值。

我尝试将其用作函数或常量,但仍收到相同的错误。

代码语言:javascript
复制
getComponent(key){
    return this.props.children!.filter(component => {
      return component.key === key;
    });
  }

我希望过滤组件的键值。也许任何人都有同样的问题?

我正在使用React-typescript

EN

回答 2

Stack Overflow用户

发布于 2019-04-05 19:00:17

正如错误所述,为this.props.children列出的字符串、数字、布尔值和其他各种类型都没有名为filter的函数。因此,您需要首先确保处理的是一个数组,然后使用类型断言告诉TypeScript:

代码语言:javascript
复制
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...
票数 0
EN

Stack Overflow用户

发布于 2019-04-05 20:20:56

几周前我遇到过一个类似的问题,我使用React.Children迭代传递给组件的嵌套子对象。

下面是我编写的代码:

代码语言:javascript
复制
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 ),并且对我来说很完美。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55533894

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档