我在互联网上搜索过。正在使用子项作为字符串而不是对象调用create元素,感谢您的帮助
这是代码
export function createElement(tag: string, props?: any, ...children: JSX.Element[]){
let el = "<"+tag+">";
if(props != undefined){
for(let i of children){
if(i == undefined)
throw new Error("Excepted class got undefined");
else{
}
}
}
el+= "</"+tag+">";
return el;
}
如何确保子元素不是字符串数组
答案 0 :(得分:0)
在运行中解析JSX字符串&#34;&#34;进入JSX.Element
的相应实例是非常有用的,并且很可能需要使用tsc来将生成的字符串转换为相应的类。不幸的是,到目前为止,我还没有看到任何可接受的解决方案。
另一方面,在大多数情况下,我已经看到你实际上不需要解析任意JSX字符串。当您使用有限的可能元素集并且它们以类似的方式实例化时,它适用。在你的例子中,你可以通过简单的开关逃脱:
let ComponentClass;
switch(tag)
{
case "MyComponent":
ComponentClass = MyComponent;
break;
case "MyOtherComponent":
ComponentClass = MyOtherComponent;
break;
// Other cases / default comes here
}
return <ComponentClass {...props}>{children}</ComponentClass>;