Reactjs 在JS中使用情感CSS,在React中使用主题

Reactjs 在JS中使用情感CSS,在React中使用主题,reactjs,theming,styled-components,emotion,Reactjs,Theming,Styled Components,Emotion,首先,我还没有反应过来,所以我还在学习如何应对 我正在跟踪关于使用的设置。但我一直在尝试在常量中使用主题颜色,该常量将在组合中使用 例如,我有: const types = { primary: (props) => css`color: ${props.theme.blue}`, secondary: (props) => css`color: ${props.theme.red}` }; const Button = withTheme(styled.button`

首先,我还没有反应过来,所以我还在学习如何应对

我正在跟踪关于使用的设置。但我一直在尝试在常量中使用主题颜色,该常量将在
组合中使用

例如,我有:

const types = {
  primary: (props) => css`color: ${props.theme.blue}`,
  secondary: (props) => css`color: ${props.theme.red}`
};

const Button = withTheme(styled.button`
  composes: ${props => types[props.type]};
`);
(这是一个人为的例子。事实上,我的
主要
次要
将有更多的CSS。)

如果渲染按钮
,则不会应用颜色。事实上,如果我检查元素,我甚至看不到
颜色
样式

但是,如果我将
按钮更改为:

const Button = withTheme(styled.button`
  composes: ${types.primary};
`);
然后我看到应用了正确的颜色


我不完全确定我做错了什么。

只是一点背景知识:

ES2015的一部分是模板文本,可以由函数通过“标记”它来解析(例如
styled.button
)。该函数接收模板文本和所有
${}
占位符,并返回结果字符串<代码>${}
可以包含任何被视为javascript表达式的内容,例如单个值、函数等

对于来自情感的
styled
,如果您将函数传递到任何占位符中,它将调用该函数,传递您使用的
styled
元素的道具(在您的示例中是
按钮
)作为第一个参数。如果使用
with theme
调用包装
styled
模板文字,则
props
参数对象将包含最初在应用程序的基本组件处提供给
的主题道具

在您的示例中,它对第二个代码块有效的原因是因为您正在传递一个将返回值的函数。在第一个代码块中,您将传递一个函数,该函数在被调用时将返回另一个函数。这意味着生成的样式将包含函数,而不是值

const types = {
  primary: (props) => css`color: ${props.theme.blue}`,
  secondary: (props) => css`color: ${props.theme.red}`
};

const Button = withTheme(styled.button`
  composes: ${props => types[props.type]};
`);
在“主要”情况下,上述评估结果为:

const Button = withTheme(styled.button`
  composes: ${props => (props) => css`color: ${props.theme.blue}`};
`);
正如你所看到的,这是一个层次太深了。主题将作为
props
的一部分传入,但是需要调用第二个更深层次的函数才能调用
css
函数。在第二个代码块中,“primary”的计算结果为:

const Button = withTheme(styled.button`
  composes: ${(props) => css`color: ${props.theme.blue}`};
`);
这将给出正确的结果,即
样式化。按钮
将传递道具,并且
css
在调用的函数中直接使用道具

希望这有点道理。这是我第一次尝试解决堆栈溢出问题,所以如果可以的话,我很乐意改进它