在Typescript中获取具有prop的子索引

时间:2018-03-06 13:11:18

标签: javascript reactjs typescript ecmascript-6

假设我有这个组件标记:

<MyComponent>
    <ComponentChild />
    <ComponentChild target />
    <ComponentChild />
</MyComponent>

如何在target中确定MyComponent的孩子的索引

我尝试了以下内容:

let index;
const childArray = React.Children.toArray(this.props.children);
const item = childArray.find((child) => {
    if (React.isValidElement(child)) {
        const clone = React.cloneElement(child as React.ReactElement<any>);
        return clone.props['target'];
    }
});
index = childArray.indexOf(item); // <-- this line causes the error

导致此错误:error TS2345: Argument of type 'string | number | ReactElement<any> | undefined' is not assignable to parameter of type 'ReactChild'.

我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

这似乎有效:

let index;
if (this.props.children) {
    React.Children.forEach(this.props.children, (child, i) => {
        if (React.isValidElement(child)) {
            const clone = React.cloneElement(child as React.ReactElement<any>);
            if (clone.props['target']) {
                index = i;
            }
        }
    });
}

仍然对我之前遇到的错误感到好奇......