Cannot Get Values from Prop in Twin.macro

点点圈 提交于 2021-01-27 21:32:48

问题


You can see an example of what I am trying to do here: https://codesandbox.io/s/vibrant-leaf-qj8vz

Note: this particular example is using Twin.macro with Styled Components. On my local computer I tried the same thing with the same results using Twin.macro with emotion/next.js.

Here is a sample component illustrating what I am trying to do:

import React from 'react'
import tw from 'twin.macro'

const Acme = ({ children, type }) => <div css={[tw`${type}`]}>{children}</div>

export default Acme

Here is how I would use that component: <Acme type="text-2xl">Text Goes Here</Acme>

My expectation is that I will be able to style this instance of the <Acme /> component via the tailwind css classes that I pass into the type prop. Instead, I get the following error message:

/src/components/Acme.js: twin.macro: Property value expected type of string but got null Learn more: https://www.npmjs.com/package/twin.macro

When trying to figure this out, I noticed something interesting that may be relevant. Here is a variation of the code that does work:

const Acme = ({ children, type }) => {
  const typeClass = 'text-2xl'
  const typeObj = {
    class: 'text-2xl',
  }

  return <div css={[tw`${typeClass}`]}>{children}</div>
}

export default Acme

Note that I have created a variable typeClass and set it to the same tailwind css class. Note, in particular, the following line of code:

css={[tw`${typeClass}`]}

I have replace the prop type with the variable typeClass. This works. But now, instead of using the variable typeClass let's use the object typeObj that I have created as follows:

const Acme = ({ children, type }) => {
  const typeClass = 'text-2xl'
  const typeObj = {
    class: 'text-2xl',
  }

  return <div css={[tw`${typeObj.class}`]}>{children}</div>
}

export default Acme

This does not work and produces the same error:

/src/components/Acme.js: twin.macro: Property value expected type of string but got null Learn more: https://www.npmjs.com/package/twin.macro

This is so even though typeClass === typeObj.class evaluates to true.

I don't know if this is helpful, but perhaps it can help indicate a solution. If I can get the type prop to behave like the typeClass variable then hopefully this would work.

Either way, any idea why this is not working and how to fix it?

Thanks.


回答1:


I found the answer (meaning that someone else answered it on a different site). Here is is. I have to rewrite both the Component and the usage of the component as follows:

// Acme.js
const Acme = ({ children, type }) => <div css={[type]}>{children}</div>

---

// App.js
import tw from "twin.macro"

<Acme type={tw`text-2xl`}>Text Goes Here</Acme>

I have tried this out and it works.



来源:https://stackoverflow.com/questions/65700495/cannot-get-values-from-prop-in-twin-macro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!