【问题标题】:React: Why not just use styles object instead of styled-components?React:为什么不只使用样式对象而不是样式组件?
【发布时间】:2017-11-17 20:43:56
【问题描述】:

我之前在 react native 中编写过应用程序,并且 我即将开始我的第一个 React 项目。我注意到一个名为 Styled Components 的工具:https://www.styled-components.com/docs/basics#motivation

但是,我看不出它有任何明显的好处,除了我可以在样式定义中进行媒体查询,所有这些都与我的组件在同一个文件中。

但是假设我有这个按钮:

import React from 'react';

const StyledButton = ({ children }) => {
  return (
    <button type="button" style={styles.button}>
      { children }
    </button>
  );
}

const styles = {
  button: {
    backgroundColor: '#6BEEF6',
    borderRadius: '12px',
    border: 'none',
    boxShadow: '0 5px 40px 5px rgba(0,0,0,0.24)',
    color: 'white',
    cursor: 'pointer',
    fontSize: '15px',
    fontWeight: '300',
    height: '57px',
    width: '331px',
  }
}

export default StyledButton;

在 styled-components 中写这个会有什么不同?是否只有我的某些样式依赖于 styled-components 发光的某些 props 的情况?

例如,这在反应中不起作用:

const StyledButton = ({ children, primary }) => {
  return (
    <button type="button" style={[styles.button, { color: primary ? 'green' : 'red' }]}>
      { children }
    </button>
  );
}

【问题讨论】:

  • 它不起作用,因为 style 属性采用对象而不是数组。 facebook.github.io/react/docs/dom-elements.html#style
  • 做这种事情的反应方式是什么?
  • 你可以将你的styles.button与style={Object.assign(styles.button, { color: primary ? 'green' : 'red' })}的新对象合并

标签: reactjs styled-components


【解决方案1】:

如果不需要伪选择器,您可以按照您的要求执行以下操作:

const StyledButton = ({ children, primary }) => {
  return (
    <button type="button" style={{ ...styles.button, color: primary ? 'green' : 'red' }}>
      { children }
    </button>
  );
}

样式化组件可能是一个更好的选择。另外,请查看Radium 作为另一种选择。也处理伪选择器和媒体查询。超级好用。

【讨论】:

    【解决方案2】:

    使用纯内联样式会遇到的一个早期障碍是缺少伪选择器:hover:active 等。 就像你提到的,你也不能使用媒体查询。

    样式化组件很棒。另请查看 Aphrodite 或 Glamourous。

    这里是其中一些库的一个很好的比较https://medium.com/seek-blog/a-unified-styling-language

    【讨论】:

    • 好点。样式化组件主要应该与哑组件一起使用吗?
    • 是的,负责展示的组件
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-11
    • 2022-06-24
    • 2021-09-22
    • 1970-01-01
    • 2018-09-10
    • 1970-01-01
    • 2011-10-01
    相关资源
    最近更新 更多