【发布时间】:2021-01-03 21:07:41
【问题描述】:
我正在尝试创建一个辅助函数,将传递的元素/组件嵌套为其自身的多个深度的子级。
像这样的
const Chain = nested(4, () => <div />)
return (
<Chain />
)
应该渲染嵌套 4 层的 div
<div>
<div>
<div>
<div />
</div>
</div>
</div>
我是这样在 React 中实现这个功能的。
/** nest the given element in itself of specified depth */
export const nested = (
depth: number,
element: () => JSX.Element
): FC<any> => () => {
let chain = element();
for (let i = 0; i < depth; i++) {
chain = React.createElement(
element().type,
element().props,
chain
);
}
return chain;
};
它正确渲染和显示嵌套的 Div,但返回一条我不明白如何更正的错误消息。
Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.
【问题讨论】:
标签: reactjs typescript error-handling components jsx