Reactjs 在React中,如何使用HOC(高阶组件)从通用组件中创建多个组件?

Reactjs 在React中,如何使用HOC(高阶组件)从通用组件中创建多个组件?,reactjs,higher-order-components,Reactjs,Higher Order Components,我已经创建了一个通用组件,用作其他组件的包装器,用作标签。以下是我的通用组件: const Label = ({ data, attribute, style, link }) => { if (link) { return ( <Link to={link} style={style}>{data ? `${data[attribute]}` : ''}</Link> ); } return ( <div st

我已经创建了一个通用组件,用作其他组件的包装器,用作标签。以下是我的通用组件:

const Label = ({ data, attribute, style, link }) => {
  if (link) {
    return (
      <Link to={link} style={style}>{data ? `${data[attribute]}` : ''}</Link>
    );
  }
  return (
    <div style={style}>{data ? `${data[attribute]}` : ''}</div>
  );
};
我想将其用作呈现不同标签组件的通用组件,例如:

const CityLabel = ({ data }) => (
  <div>{data ? `${data.city}` : ''}</div>
  )

等等

如何使用HOC来执行此操作?

此示例假设UserLabel仅呈现name而不是firstName&lastName,因为您的标签组件无法处理两个属性

const Label = ..., 
makeLabel = (
    (Label) => (mapLabelProps) => (props) => 
        <Label {...mapLabelProps(props)} />
)(Label),
CityLabel = makeLabel(({data, style, link}) => ({
    data,
    attribute: 'city',
    style,
    link
})),
UserLabel = makeLabel(({user, style, link}) => ({
    data: user,
    attribute: 'name',
    style,
    link
}));

render(){
    return (
        <div>
            <CityLabel data={{city:"NYC"}} />
            <UserLabel user={{name:"obiwan"}} />
        </div>
    )
}
const Label = ..., 
makeLabel = (
    (Label) => (mapLabelProps) => (props) => 
        <Label {...mapLabelProps(props)} />
)(Label),
CityLabel = makeLabel(({data, style, link}) => ({
    data,
    attribute: 'city',
    style,
    link
})),
UserLabel = makeLabel(({user, style, link}) => ({
    data: user,
    attribute: 'name',
    style,
    link
}));

render(){
    return (
        <div>
            <CityLabel data={{city:"NYC"}} />
            <UserLabel user={{name:"obiwan"}} />
        </div>
    )
}