假设我们在其定义中使用Button
组件使用className
进行样式设置:
const Button = props => (
const { children, ...otherProps } = props
<button className={styles.someClass} {...otherProps}> {props} </button>
)
我在容器中使用此组件,但我需要再次传递特定于该容器的类名,因此<Button className={styles.red}>Some Text</Button>
这意味着我现在收到错误,因为我传入了额外的className,并在每个组件中定义类似的内容:
const Button = props => (
const { children, className, ...otherProps } = props
<button className={`${styles.someClass} ${className}`} {...otherProps}> {props} </button>
)
看起来像过度工作,所以我想看看是否有一个常见的做法来处理这个用例。
答案 0 :(得分:0)
首先,我强烈建议https://github.com/JedWatson/classnames它与React的效果非常好。
我如何处理这些案例是有一个名为classNames
的按钮,它会接受一个字符串。然后在Button组件中,您可以执行类似
function getButtonClass() {
let classes = this.props.classNames ? this.props.classNames : '';
classes += // whatever additional classes you need to add
return classes
}
然后你有一个包含的函数,可以像你需要的那样复杂和健壮。
最后产品将是
<button className={getButtonClass()} {...otherProps}> {props} </button>