React-如何确定特定的子组件是否存在?
如果我有这个结构:
const MyComponent = (props) => { return (
<Wrapper />{props.children}</Wrapper>
);
}
我这样使用它:
<MyComponent> <SomeInnerComponent />
</MyComponent>
我如何从函数内部查看是否<SomeInnerComponent
/>明确包含在之间?<MyComponent></MyComponent>``MyComponent
回答:
鉴于您要检查SomeInnerComponent
是否存在儿童,可以执行以下操作
const MyComponent = (props) => { for (let child in props.children){
if (props.children[child].type.displayName === 'SomeInnerComponent'){
console.log("SomeInnerComponent is present as a child");
}
}
return (
<Wrapper />{props.children}</Wrapper>
);
}
或者您可以在组件上进行propTypes验证
MyComponent.propTypes: { children: function (props, propName, componentName) {
var error;
var childProp = props[propName];
var flag = false;
React.Children.forEach(childProp, function (child) {
if (child.type.displayName === 'SomeInnerComponent') {
flag = true
}
});
if(flag === false) {
error = new Error(componentName + ' does not exist!'
);
}
return error;
}
},
以上是 React-如何确定特定的子组件是否存在? 的全部内容, 来源链接: utcz.com/qa/421168.html