如何用 React Hook 替换剥离 props 并分配类名的 HOC?

How to replace an HOC that strips props and assigns classnames with react hooks?

现在我有一个高阶组件,可以让我榨取任何组件,它:

看起来像这样:

// withColor.js
import React from 'react'
import styles from './withColor.css'
import cn from 'classnames'

const withColor = TargetComponent => {
  const WrappedComponent = props => {
    // color is something like "black" or "red" and has a matching css class
    const { className, color, ...rest } = props
    const enhancedClassName = cn(className, {
      [styles[`Color-${color}`]]: color,
    })
    return <TargetComponent className={enhancedClassName} {...rest} />
  }
  return WrappedComponent
}

用法示例:

// box.js
import React from 'react'
import withColor from '../hocs/withColor'

const Box = props => <div data-box {...props} />

export default withColor(Box)

我可以使用 React Hooks 来代替吗?它会是什么样子?

您只需编写一个执行上述逻辑的自定义挂钩。事实上,它甚至不是一个钩子,而是一个通用函数

const useWithColor = (props) => {
   const { className, color, ...rest } = props
    const enhancedClassName = cn(className, {
      [styles[`Color-${color}`]]: color,
    })
   return {...rest, enhancedClassName};
}

并像

一样使用它
export default props =>  {
   const dataProps = useWithColor(props);
   return <div data-box {...dataProps} />
}