0

我正在尝试使用 Radium 编写干净和干燥的代码样式。到目前为止,这就是我的按钮。

/**
*
* Button
*
*/

import React, { PropTypes } from 'react';
import Radium from 'radium';

const styles = {
  base: {
    borderRadius: '3px',
    backgroundColor: '#23cdf4',
    fontSize: '13px',
  },
  primaryBlue: {
    backgroundColor: '#23cdf4',
  },
  primaryBlueBig: {
    borderRadius: '8px',
    fontSize: '16px',
    padding: '14px 28px',
  },
  primaryRed: {
    backgroundColor: '#F99CAC',
  },
};

class Button extends React.Component {

  constructor(props) {
    super(props);
  }

  render() {
    return (
      <button
        style={[styles.base, styles[this.props.type], this.props.style]}
      >
        {text}
      </button>
    );
  }
}

Button.propTypes = {
  text: PropTypes.any,
  type: PropTypes.oneOf(['primaryBlue', 'primaryBlueBig']).isRequired,
  style: PropTypes.object,
  disabled: PropTypes.bool,
};

export default Radium(Button);

有两件事我想不通:

  1. 如何在不重复自己的情况下将 primaryBlue 使用的背景颜色扩展到 primaryBlueBig?
  2. 如果禁用为真,如何更改两个蓝色按钮的背景颜色?

这是我目前正在使用的精简版本,并试图摆脱在渲染功能中出现巨大的 if else 块。谢谢!^.^

4

1 回答 1

1

您可以使用修饰符

这基本上是您已经在做的事情,但需要进行更多重构。

我会稍微不同地定义样式:

const styles = {
  base: {
    borderRadius: '3px',
    backgroundColor: '#ffffff',
    fontSize: '13px',
  },

  primaryBlue: {
    backgroundColor: '#23cdf4',
  },
  primaryRed: {
    backgroundColor: '#F99CAC',
  },

  big: {
    borderRadius: '8px',
    fontSize: '16px',
    padding: '14px 28px',
  },

  disabled: {
    primaryBlue: {
      backgroundColor: '#eeeeee',
    },
    primaryRed: {
      backgroundColor: '#eff0f1',
    }
  }
};

然后你可以有一个big和一个disabled道具。

return (
  <button
    style={[
      styles.base,
      styles[this.props.type],
      this.props.big && styles.big,
      this.props.disabled && styles.disabled[this.props.type]
    ]}>
    {text}
  </button>
);
于 2017-05-14T00:50:19.707 回答