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

In React, how can I use HOC (High Order Component) to create several components out of a generic component?

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

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>
  )

const UserLabel = ({ user }) => (
  <div>{user ? `${user.firstName} ${user.lastName}` : ''}</div>
  )

等...

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

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

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>
    )
}