现在我有一个高阶组件,它可以使任何组件榨汁,
color
道具它看起来像这样:
// 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挂钩代替吗?会是什么样?
答案 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} />
}