Solid JSX中的动态标签名称



我想在SolidJS中动态设置JSX标签名称。我来自React,在那里做起来相当简单:

/* Working ReactJS Code: */
export default MyWrapper = ({ children, ..attributes }) => {
const Element = "div";
return (
<Element {...attributes}>
{children}
</Element>
)
}

但是当我尝试在SolidJS中做同样的事情时,我得到以下错误:

/* Console output when trying to do the same in SolidJS: */
dev.js:530 Uncaught (in promise) TypeError: Comp is not a function
at dev.js:530:12
at untrack (dev.js:436:12)
at Object.fn (dev.js:526:37)
at runComputation (dev.js:706:22)
at updateComputation (dev.js:691:3)
at devComponent (dev.js:537:3)
at createComponent (dev.js:1236:10)
at get children [as children] (Input.jsx:38:5)
at _Hot$$Label (Input.jsx:7:24)
at @solid-refresh:10:42

我想知道我是否在这里错过了什么,或者是否有可能在SolidJS中以任何其他方式实现这一点。

Solid有辅助组件。

import { Dynamic } from "solid-js/web";
<Dynamic component="div" {...attributes}>
{props.children}
</Dynamic>

下面是另一种实现,它涵盖了字符串和节点等简单情况,不过您可以将其扩展为涵盖任何JSX元素:

import { Component, JSXElement} from 'solid-js';
import { render,  } from 'solid-js/web';
const Dynamic: Component<{ tag: string, children: string | Node }> = (props) => {
const el = document.createElement(props.tag);
createEffect(() => {
if(typeof props.children === 'string') {
el.innerText = String(props.children);
} else if (props.children instanceof Node){
el.appendChild(props.children);
} else {
throw Error('Not implemented');
}
});
return el;
};
const App = () => {
return (
<div>
<Dynamic tag="h2">This is an H2!</Dynamic>
<Dynamic tag="p">This is a paragraph!</Dynamic>
<Dynamic tag="div"><div>Some div element rendering another div</div></Dynamic>
</div>
)
}
render(App, document.body);

这是有效的,因为Solid组件被编译成本机DOM元素,但是由于我们没有转义输出,因此直接呈现任何子元素是危险的,因为您无法控制内容。

当您需要从内容可编辑或文本区域呈现富文本时,这种替代方法很方便,文本包括em,strong等标记。只要确保使用innerHTML属性而不是innerText

最新更新