2

I have this simple Higher-Order Component that works fine but it only accepts a single component:

let VerticalSlider = (Komponent) => {
  return (props) => (
    <div className='slider'>
      <Komponent {...props}/>
    </div>
  );
};

How would one rewrite the HOC to accept multiple components (unknown number) and return them as siblings (one by one under eachother) together with their respective props?

I assume this is how you'd call a HOC with multiple components as it's just a function:

VerticalSlider(MyComponent, MyOtherComponent)

I know how to accept and destruct an unknown number of "normal" props, but I'm a but lost here when it comes to passed in components.

4

1 回答 1

2

你可以这样做:

import React, { Component } from 'react';
import { render } from 'react-dom';

let VerticalSlider = (...komponents) => {
  return (props) => (
    <div className='slider'>
      { komponents.map((K, i) => <K {...props.ps[i]} /> ) }
    </div>
  );
};

const Apple = props =>
  <div>{ props.name }</div>;

const Orange = props =>
  <div>{ props.desc }</div>;

const MyComp = VerticalSlider(Apple, Orange);

const App = () =>
  <div>
    Hello
    <MyComp 
      ps={[{ name: 'apple' }, { desc: 'orange' }]} />
  </div>

render(<App />, document.getElementById('root'));

但这有点难看,你的同事会讨厌你。保持简单,不要想太多。这是一个演示

于 2018-01-17T22:33:10.803 回答