reactjs - Emotion.js 如何在对象样式中使用动态样式?
问题描述
import styled from '@emotion/styled'
import { css } from '@emotion/core'
const dynamicStyle = props =>
css`
color: ${props.color};
`
const Container = styled.div`
${dynamicStyle};
`
render(
<Container color="lightgreen">
This is lightgreen.
</Container>
)
如何Container
使用以下对象样式制作?
const H1 = styled.h1(
{
fontSize: 20
},
props => ({ color: props.color })
)
解决方案
这是你从文档中复制的一个不好的例子,它实际上导致color
道具被写入容器 div,但本质上你会做这样的事情:
import styled from '@emotion/styled'
import { css } from '@emotion/core'
const dynamicStyle = props => ({ color: props.color })
const Container = styled.div`
${dynamicStyle};
`
render(
<Container color="lightgreen">
This is lightgreen.
</Container>
)
为了理智和避免道具被传递给你的 React 元素,我推荐一种更像这样的方法:
const Container = styled.div`
color: ${props => props.color};
`
// or...
const Container = ({ color, ...props }) => <div css={{ color }} {...props} />
推荐阅读
- node.js - 如果没有为 module.exports 分配任何内容,Node.js 'require()' 会返回什么
- mongodb - 嵌套数组求和/计数 MongoDB Express
- linux - 运行 Bash 脚本时找不到命令,但直接运行命令时有效
- html - 跨越 2 列和 2 行的 Flexbox 单元格
- modelica - 为什么在算法部分中分配任何一个元素时,Modelica数组元素会自动分配为零
- sql - SQL Server:SUM 任务每日累计工作量
- arrays - 这段代码是如何工作的?他们正在根据条件删除数组中的项目。语法让我困惑
- c++ - C++ 中 std::vector 的压缩布尔特性
- java - 什么时候可以在从 Java 源代码编译的 .class 文件中获取 pop2 操作码?
- javascript - React Native Animated 组件在平移时被覆盖