4

我以前用 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 中写这个会有什么不同?是否只有我的某些样式依赖于某些props样式组件闪耀的情况?

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

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

2 回答 2

2

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

样式化组件很棒。另请查看阿芙罗狄蒂或魅力四射。

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

于 2017-06-15T12:36:14.910 回答
2

如果不需要伪选择器,您可以像这样询问:

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

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

于 2017-06-15T13:23:17.240 回答