【发布时间】: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' })}的新对象合并