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

问题描述 投票:0回答:1

假设我有这个组件标记:

<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'.

我在这做错了什么?

javascript reactjs typescript ecmascript-6
1个回答
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;
            }
        }
    });
}

我还以前对这个错误感到好奇......

© www.soinside.com 2019 - 2024. All rights reserved.