我在 React 中实现了一个来自这篇文章的“插槽”系统:Vue Slots in React .但是,由于 Enzyme 包装器的子项和 React 的子项之间的“不匹配”,我在尝试测试该组件时遇到了麻烦。
这是从 React 获取“slot”子项的函数 children
.当与 children
一起提供时,该函数在应用程序组件中按预期工作。 prop,但在测试期间不起作用,因为“子项”与 React.children
的格式不同.
const getSlot = (children, slot) => {
if (!children) return null;
if (!Array.isArray(children)) {
return children.type === slot ? children : null;
}
// Find the applicable React component representing the target slot
return children.find((child) => child.type === slot);
};
TestComponent
不直接用于测试,但旨在展示如何在组件中实现“插槽”的示例。
const TestComponent = ({ children }) => {
const slot = getSlot(children, TestComponentSlot);
return (
<div id="parent">
<div id="permanentContent">Permanent Content</div>
{slot && <div id="optionalSlot">{slot}</div>}
</div>
);
};
const TestComponentSlot = () => null;
TestComponent.Slot = TestComponentSlot;
这是我尝试编写的测试的基础。本质上,创建一个 super 基本组件树,然后检查组件的子组件是否包含预期的“插槽”组件。然而,getSlot
函数总是 返回null
因为输入与 React 提供的输入不同 children
在应用程序中使用时。
it("Finds slots in React children", () => {
const wrapper = mount(
<div>
<TestComponent.Slot>Test</TestComponent.Slot>
</div>
);
// Unsure how to properly get the React children to test method.
// Below are some example that don't work...
// None of these approaches returns React children like function expects.
// Some return null and other return Enzyme wrappers.
const children = wrapper.children();
const { children } = wrapper.instance();
const children = wrapper.children().instance();
// TODO: Eventually get something I can put into function
const slot = getSlot(children, TestComponentSlot);
});
如有任何帮助或见解,我们将不胜感激!
最佳答案
这里的问题是,当您使用 enzyme 的 children()
方法时,它会返回 ShallowWrapper
[ 1 ].为了让子组件成为 React 组件,您必须直接从 props 方法中获取它们。
因此,以这种方式派生 child :
const children = wrapper.props().children;
关于javascript - 如何从 Enzyme 获取 React children,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58296160/