css - 使用 CSS 模块防止大量与样式相关的 React Prop

标签 css reactjs css-modules

在我的元素中,我有一个Text组件:

import React from 'react'
import { bool, string, number, element, func, object, any } from 'prop-types'
import cx from 'classnames'
import s from './styles/Text.css'


const Text = (props) => {
  const renderMultiLines = () => {
    const items = props.children.split(' ')
    return items.map(text => <div style={{ marginBottom: '2px' }} className={s.multiLineItem}>{text}</div>)
  }

  return (
    <div
      className={cx(
        s.text,
        props.ellipsis && s.ellipsis,
        props.isUpperCase && s.isUpperCase,
        props.isBold && s.bold,
        props.isExtraBold && s.extraBold,
        props.isExtraSpaced && s.extraSpaced,
        props.multiLine && s.multiLine,
        props.active && s.underlined,
        props.active && s.primary,
        s[props.color],
        s[props.size],
      )}
      onClick={props.onClick}
      style={props.style}
    >
      {!props.multiLine && props.children}
      {props.multiLine && renderMultiLines()}
    </div>
  )
}

Text.defaultProps = {
  isBold: false,
  isExtraSpaced: false,
  isExtraBold: false,
  children: '',
  color: '',
  ellipsis: false,
  size: 'extraExtraSmall',
  isUpperCase: false,
  onClick: undefined,
  style: {},
  active: false,
}

Text.propTypes = {
  isBold: bool,
  isExtraSpaced: bool,
  isExtraBold: bool,
  children: any,
  color: string,
  ellipsis: bool,
  size: string,
  isUpperCase: bool,
  onClick: func,
  style: object,
  active: bool,
}

export default Text

如您所见,目的是传递 props 来更改文本的布局。

我们的想法是,您最终只会得到有限数量的文本样式,而不会出现细微的变化。

这个组件在我的元素中的用法示例如下所示:

<Text
  onClick={() => this.handleGlobalChangeDate(Number(n))}
  isBold
  size="medium"
  color="primary"
  active={Number(n) === activeDay && visibleMonth === activeMonth}
>{n}</Text>

这看起来很乱,我觉得isBoldsizecolor等应该不需要显示在这里作为props传入.相反,它们应该在 CSS 中处理并引用元素的 variables.css 文件。

通过这种方式,我希望能够将 className 附加到相关的 Text 组件。

但是,因为它是一个组件而不是简单的 div,例如,className 只会作为 prop 传递给组件。

我如何使用 CSS 来处理这个问题,而不是使用大量与样式相关的 Prop ?

最佳答案

尝试 classnames ,一种基于 Prop 或状态动态添加类的好方法。

有了这个你可以做:

var btnClass = classNames({
  btn: true,
  'btn-pressed': this.state.isPressed,
  'btn-over': !this.state.isPressed && this.state.isHovered
});
return <button className={btnClass}>{this.props.label}</button>;

然后在你的组件中应用:

<div className={btnClass}>Something</div>

关于css - 使用 CSS 模块防止大量与样式相关的 React Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43737612/

相关文章:

html - 是否可以使用 CSS 为禁用的 INPUT 元素设置样式?

css - 在任何分辨率下垂直调整 div #Mobile Web Application

reactjs - 如何在 React Native 中让父级的宽度包裹其内容?

javascript - 如何将一个 React 类的 props 传递给另一个 React 类?

css - 在 React 中如何只导入需要的 Bootstrap 样式。 Bootstrap css 模块?

CSS : Div with transparent image at the bottom

javascript - 使用 jQuery 向下滚动到图像底部时使用图像在 div 中设置动画

javascript - 如何防止浏览器重复获取相同的href

javascript - 在 next.js 中将 Prop 作为类名传递

create-react-app - 带有 react-scripts@next 和 css 模块的故事书