gpt4 book ai didi

reactjs - 使用 instanceof 测试 React 组件的基类

转载 作者:搜寻专家 更新时间:2023-10-30 20:54:08 24 4
gpt4 key购买 nike

为了支持嵌套导航菜单,我们使用 React.cloneElement 向子菜单组件添加属性(菜单组件是自定义组件,基于 react-bootstrap)。为了防止我们克隆所有元素,即使它们不是子菜单组件,而是常规内容组件,我希望克隆有条件。

所有菜单组件都是“MenuBase”的子类(它本身是 React.Component 的子类)。在我的代码中,我尝试测试 React 组件的子组件(通过使用 React.Children 实用函数读取 this.props.children)是否是 MenuBase 的实例。

简化代码:

interface IMenuBaseProps {
// menu related properties
}

abstract class MenuBase<P extends IMenuBaseProps, S> extends React.Component<P, S> {
// constructor etc.
}

interface IGeneralMenuProps extends IMenuBaseProps {
// additional properties
}

class GeneralMenu extends MenuBase<IGeneralMenuProps, {}> {
public render(): JSX.Element {
// do some magic
}
}

在菜单逻辑的某处我想做如下的事情

React.Children.map(this.props.children, (child: React.ReactElement<any>): React.ReactElement<any> ==> {
if (child instanceof MenuBase) {
// return clone of child with additional properties
} else {
// return child
}
}

但是,此测试永远不会产生 true,因此永远不会进行克隆。

在 Chrome 开发者工具中我可以看到:

  1. child.type = function GeneralMenu(props)
  2. child.type.prototype = MenuBase

typescript child watch

谁能帮我澄清一下:

  1. 为什么 instanceof 不工作
  2. 如果我不能对 React 组件的继承链中的某些东西使用测试实例,我有什么选择(我知道我可以测试 IMenuBaseProps 的一个属性是否存在,但我不知道我真的不喜欢那个解决方案)。

最佳答案

查看 definition file , ReactChildren.map定义如下:

map<T>(children: ReactNode, fn: (child: ReactChild, index: number) => T): T[];

ReactChild然后定义如下:

type ReactChild = ReactElement<any> | ReactText;

您的情况可能是 ReactElement这是:

interface ReactElement<P> {
type: string | ComponentClass<P> | SFC<P>;
props: P;
key?: Key;
}

你的 MenuBasetype,所以它可能应该是:

React.Children.map(this.props.children, (child: React.ReactElement<any>): React.ReactElement<any> ==> {
if (child.type === MenuBase) {
// return clone of child with additional properties
} else {
// return child
}
}

child.type 似乎是组件的类而不是实例,因此您需要执行 而不是执行 child.type instanceof MenuBase >child.type === MenuBase


编辑

在尝试了一些事情之后我想到了这个解决方案:

React.Children.map(this.props.children, (child: React.ReactElement<any>): React.ReactElement<any> ==> {
if (MenuBase.isPrototypeOf(child.type)) {
// return clone of child with additional properties
} else {
// return child
}
}

如果你想检查 child 是否是 GeneralMenu 那么你需要做:

child.type.prototype === GeneralMenu.prototype

关于reactjs - 使用 instanceof 测试 React 组件的基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39387405/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com