如何用HOOK钩替换剥除道具并分配类名的HOC?

时间:2019-03-14 18:49:02

标签: reactjs react-hooks

现在我有一个高阶组件,它可以使任何组件榨汁,

  • 允许组成一个color道具
  • 将颜色的css类传递给组件一个className
  • 不会将颜色道具传递给组件

它看起来像这样:

// 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挂钩代替吗?会是什么样?

1 个答案:

答案 0 :(得分:2)

您所需要做的就是编写一个执行上述逻辑的自定义钩子。实际上,它甚至不是一个钩子,而是一个常用功能

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} />
}
相关问题