Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用动态组件或标记包装子对象_Javascript_Reactjs_Jsx - Fatal编程技术网

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>