【问题标题】:React tailwind, cannot pass tailwind css from parent to child反应顺风,不能将顺风CSS从父母传递给孩子
【发布时间】:2022-03-15 03:25:53
【问题描述】:

我遇到了一个简单的问题,在快速谷歌搜索或 Tailwind 文档中似乎没有答案。

我是 Vuejs 用户,但我已经开始学习 React。我选择使用 TailwindCSS 来测试我的 React 应用程序,但我注意到 Vuejs 和 React 之间的 Tailwind 用法存在一些差异。

在 Vue 中,我可以像这样通过父组件控制子组件:

Parent component:
<template>
 <div class="w-screen">
  <ChildComponent class="w-1/2 mx-auto" />
 </div>
</template>

孩子可以通过上面的父组件在屏幕上居中,就像在 ChildComponent 的类中一样。

但是,当我尝试在 React 中做同样的事情时:

Parent component:
import Homepage from './views/Homepage';

function App() {
  return (
    <div className='bg-black w-screen'>
      <Homepage className="w-1/2 mx-auto"/>
    </div>
  );
}

export default App;

当我将 CSS 放置在父级的 Homepage 子组件中时,什么都没有发生。

我确信有一个简单的答案,但我不打算搜索文档或使用任何关键字来查找此问题。有人得到提示或确认这是在 React 中使用的,还是我在安装时做错了什么?

【问题讨论】:

    标签: reactjs tailwind-css


    【解决方案1】:

    这不是一个 Tailwind 问题,而是一个 React 问题。你不能在 Homepage 组件上使用 className 而不将其作为道具传递。在您的情况下,Homepage 不期待任何className。因此,在制作主页组件时,您必须提供一个名为“className”的道具,然后它才能正常工作。 或者,如果您只是使用div 代替主页,它将正常工作。看看这个codesandbox link

    【讨论】:

    • 谢谢,添加 div 更有意义。否则,每次我在父组件上设置一些东西时,我都必须在子组件上传递一个道具。
    【解决方案2】:

    你需要考虑到&lt;Homepage/&gt; 是一个 React 组件,不能像这样接受 HTMLAttrs。 这个例子可能会清除它:

    const app = () => {
        <div className="bg-black">
            <Homepage className="bg-red" />
        </div>
    }
    
    const homePage = (props) => {
        <div className={props.className}>
            <h1 className="bg-red">hi</h1>
        </div>
    }
    

    您传递给&lt;Homepage/&gt;className 实际上是一个道具而不是Html 属性。

    【讨论】:

      【解决方案3】:

      在 Vue 中它相当简单,但在反应中你需要明确并在你的组件中使用 className

      // Creating component
      const Button = ({ className, children }) => {
        return <button className={`${className} bg-red-500`}>{children}</button>
      }
      
      export default Button
      
      // Using component
      <Button className="text-white">MyButton</Button>
      

      【讨论】:

        猜你喜欢
        • 2020-04-06
        • 2020-09-19
        • 2018-03-29
        • 1970-01-01
        • 2015-03-22
        • 2021-12-31
        • 2020-07-22
        • 2020-10-31
        • 2022-09-26
        相关资源
        最近更新 更多