Javascript 如何使用动态组件或标记包装子对象
我想制作一个Javascript 如何使用动态组件或标记包装子对象,javascript,reactjs,jsx,Javascript,Reactjs,Jsx,我想制作一个组件或函数,用给定的参数包装给定的组件 例如: // Input wrapComponent(ComponentToWrap, ['div', 'main', 'span']); // Output must be equivalent to this: <div> <main> <span> <ComponentToWrap /> </span> </main> </
组件
或函数
,用给定的参数包装给定的组件
例如:
// Input
wrapComponent(ComponentToWrap, ['div', 'main', 'span']);
// Output must be equivalent to this:
<div>
<main>
<span>
<ComponentToWrap />
</span>
</main>
</div>
//输入
wrapComponent(组件拖缆,['div','main','span']);
//输出必须与此等效:
//输入
wrapComponent(ComponentToRap,['div','main',SomeParentComponent]);
//输出必须与此等效:
包装器数组可以是任何大小的0到10+
我没有尝试任何东西,因为我不知道如何动态地实现它。
任何答案都将不胜感激。试试以下方法:
constwrappcomponent=(组件,包装器)=>{
constall=[…包装器,组件];
const create=i=>{
常数C=所有[i];
如果(!all[i])返回null;
if(typeof C=='string')
返回React.createElement(all[i],null,create(i+1));
返回{create(i+1)}
}
返回创建(0);
}
常量测试=({children})=>测试{children}
const Test2=()=>我在这里!
const MyComponent=()=>{wrapComponent(Test2,['div',span',Test,'span'])
ReactDOM.render(
,
document.getElementById(“应用程序”)
);代码>
试试这个:
constwrappcomponent=(组件,包装器)=>{
constall=[…包装器,组件];
const create=i=>{
常数C=所有[i];
如果(!all[i])返回null;
if(typeof C=='string')
返回React.createElement(all[i],null,create(i+1));
返回{create(i+1)}
}
返回创建(0);
}
常量测试=({children})=>测试{children}
const Test2=()=>我在这里!
const MyComponent=()=>{wrapComponent(Test2,['div',span',Test,'span'])
ReactDOM.render(
,
document.getElementById(“应用程序”)
);代码>
谢谢@Yosef。我根据自己的需要重构了你的代码,现在它可以正常工作了。谢谢@Yosef。我根据我的需要重构了你的代码,现在它可以按照我的要求工作了
// Input
wrapComponent(ComponentToWrap, ['div', 'main', SomeParentComponent]);
// Output must be equivalent to this:
<div>
<main>
<SomeParentComponent>
<ComponentToWrap />
</SomeParentComponent>
</main>
</div>