首页 > 解决方案 > 用 TypeScript 反应有类型的孩子

问题描述

我是新手,我在访问 children 数组时遇到了问题。我有一个这样的组件:

class MyComponent extends React.Component {
    constructor(props: any) {
        super(props);
    }
    doSomething(): void {
    }
    render() {
        return <span>Test</span>
    }
}

该应用程序是:

function App() {
    return <MyContainer>
        <MyComponent />
        <br />
        <MyComponent />
        <br />
        <MyComponent />
    </MyContainer>;
}

MyContainer 是这样制作的组件:

class MyContainer extends React.Component {
    OnClickHandler() {
        React.Children.forEach(this.props.children, c => {
            // if ([[Check if c is MyComponent]]) {
            //     //c.doSomething();
            // }
        });
    }
    render() {
        return <React.Fragment>
            {this.props.children}
            <br />
            <input type="button" onClick={this.OnClickHandler} value="ClickMe" />
        </React.Fragment>
    }
}

如何检查子组件是否属于 MyComponent 类型并获取它的实例?

标签: reactjstypescript

解决方案


无论最终目标是什么,可能有比操纵孩子更好的方法来实现它。这通常不是一个好的设计。

您需要更改OnClickHandler为箭头功能才能访问this.props.children. 否则this指函数的本地上下文。

如果您记录孩子,您将看到它们是具有属性typekeyref和的对象props。这与 typescript 认为的不同,即ReactNode. 所以下面的代码会有打字稿错误。但它确实正确识别了哪些孩子MyComponent

OnClickHandler = () => {
  console.log(this.props.children)
    React.Children.forEach(this.props.children, (child, index) => {
      if (child?.type === MyComponent) {
        console.log("yes");
      } else {
        console.log("no")
      }
    });
}

这不会做你想做的事,因为这些child对象没有doSomething()属性。

didClick以组件获得属性的方式设计它更有意义。


推荐阅读