reactjs - 用 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 类型并获取它的实例?
解决方案
无论最终目标是什么,可能有比操纵孩子更好的方法来实现它。这通常不是一个好的设计。
您需要更改OnClickHandler
为箭头功能才能访问this.props.children
. 否则this
指函数的本地上下文。
如果您记录孩子,您将看到它们是具有属性type
、key
、ref
和的对象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
以组件获得属性的方式设计它更有意义。
推荐阅读
- gcc - 尝试实现观察者模式并得到分段错误(请帮助)c ++
- php - php中的日期问题
- swift - Swift 解码和编码自定义类型
- c# - 无法通过 MediatR 使用范围服务
- wordpress - WordPress Polylang 不显示语言图标
- python - 在 Python 中循环访问 API GET 请求的 API 值数组
- objective-c - 从窗口菜单中删除与选项卡相关的功能?
- javascript - FireBase 调度功能不保存到实时数据库
- python - Pyglet 图像绘制问题
- azure - Azure 发布管道不断将“.scm”添加到 appservice 的 URL