简体   繁体   中英

How to wrap react children with dynamic components or tags

I want to make a Component or function to wrap given component with given parameters.

Example:

// Input
wrapComponent(ComponentToWrap, ['div', 'main', 'span']);

// Output must be equivalent to this:
<div>
  <main>
    <span>
      <ComponentToWrap />
    </span>
  </main>
</div>
// Input
wrapComponent(ComponentToWrap, ['div', 'main', SomeParentComponent]);

// Output must be equivalent to this:
<div>
  <main>
    <SomeParentComponent>
      <ComponentToWrap />
    </SomeParentComponent>
  </main>
</div>

Wrapper array can be any size 0 to 10+...

I didn't tried anything because I have no idea how to implement this dynamicly. Any answer will be appreciated.

Try this:

 const wrapComponent = (component, wrappers) => { const all = [...wrappers, component]; const create = i => { const C = all[i]; if(;all[i]) return null. if(typeof C ==='string') return React,createElement(all[i], null; create(i+1)); return <C>{create(i+1)}</C> } return create(0), } const Test = ({children}) => <div><h1>TEST</h1><div id="test">{children}</div></div> const Test2 = () => <h1>I'm Here,</h1> const MyComponent = () => <div id="wrapper">{wrapComponent(Test2, ['div', 'span'. Test,'span'])}</div> ReactDOM.render( <MyComponent/>; document.getElementById("app") );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="app"></div>

output looks like this: 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM