【发布时间】:2021-04-18 09:08:52
【问题描述】:
你可以在这里看到我正在尝试做的一个例子:https://codesandbox.io/s/vibrant-leaf-qj8vz
注意:这个特殊的例子是使用带有样式组件的Twin.macro。在我的本地计算机上,我使用 Twin.macro 和 Emotion/next.js 尝试了相同的结果。
这是一个示例组件,说明了我正在尝试做的事情:
import React from 'react'
import tw from 'twin.macro'
const Acme = ({ children, type }) => <div css={[tw`${type}`]}>{children}</div>
export default Acme
我将如何使用该组件:<Acme type="text-2xl">Text Goes Here</Acme>
我的期望是,我将能够通过我传递给 type 属性的 tailwind css 类来设置 <Acme /> 组件的这个实例的样式。相反,我收到以下错误消息:
/src/components/Acme.js: twin.macro: Property value expected type of string but got null Learn more: https://www.npmjs.com/package/twin.macro
当我试图弄清楚这一点时,我注意到一些有趣的可能相关的东西。下面是一个有效的代码变体:
const Acme = ({ children, type }) => {
const typeClass = 'text-2xl'
const typeObj = {
class: 'text-2xl',
}
return <div css={[tw`${typeClass}`]}>{children}</div>
}
export default Acme
请注意,我创建了一个变量 typeClass 并将其设置为相同的顺风 css 类。请特别注意以下代码行:
css={[tw`${typeClass}`]}
我已经用变量typeClass 替换了道具type。这行得通。但是现在,我们不使用变量typeClass,而是使用我创建的对象typeObj,如下所示:
const Acme = ({ children, type }) => {
const typeClass = 'text-2xl'
const typeObj = {
class: 'text-2xl',
}
return <div css={[tw`${typeObj.class}`]}>{children}</div>
}
export default Acme
这不工作并产生相同的错误:
/src/components/Acme.js: twin.macro: Property value expected type of string but got null Learn more: https://www.npmjs.com/package/twin.macro
即使typeClass === typeObj.class 的计算结果为true,情况也是如此。
我不知道这是否有帮助,但也许它可以帮助指出解决方案。如果我可以让 type 属性的行为类似于 typeClass 变量,那么希望这会起作用。
无论哪种方式,知道为什么这不起作用以及如何解决它吗?
谢谢。
【问题讨论】:
-
我看到你找到了解决办法,这很好!虽然我必须说那个错误 imo 它是来自 Twin.macro 的错误。这是一个有效的 javascript 语法,并且您确实传递了一个字符串作为参数。
-
@buzatto Twin.macro 的“所有者”解释了它为什么不起作用:Twin 是一个 babel 插件,babel 插件不会执行你编写的 javascript,它们让你遍历它并定制东西。 Babel 没有能力去搜索你在 tw 中定义的变量——它可以做非常基本的执行,但只有当它正在寻找的变量被明确定义时。这是他写的链接:github.com/ben-rogerson/twin.macro/issues/…
标签: javascript reactjs styled-components tailwind-css emotion