【问题标题】:Tailwind CSS responsive classes not working with Rails ViewComponent gemTailwind CSS 响应类不适用于 Rails ViewComponent gem
【发布时间】:2022-10-19 00:45:28
【问题描述】:

我将 ViewComponent gem 与 Tailwind CSS 一起使用。我使用 <%= render ExampleComponent.new(resource: @resource) %> 从我的视图文件中渲染组件。在我的 app/components 目录中,我有 example_component.rb 和 example_component.html.erb 文件。该组件渲染良好。但是,如果我有使用响应式实用程序变体的 Tailwind CSS 类,那么无论它们是否有效,都会受到影响。例如,假设我正在使用视图组件进行渲染:

# app/components/example_component.rb
class ExampleComponent < ViewComponent::Base
  def initialize(resource:)
    @resource = resource
  end
end

带有视图组件 html.erb 文件:

# app/components/example_component.html.erb
<%= form_with url: resource_path, target: '_top', class: 'mb-2 md:mb-0' do |f| %>
  <%= f.hidden_field :resource_id, value: @resource.id %>
  <%= f.submit 'Submit', class: "w-full md:w-fit" %>
<% end %>

当显示为中 (md) 或更大时,Tailwind 类使底部边距从 2 更改为 0。此外,当显示为中等或更大时,提交按钮会从宽度 100% 更改为宽度适合内容。如果我从视图目录中的部分使用通常的 Rails 渲染来渲染它,它可以正常工作。如果我使用 ViewComponent 类呈现完全相同的 html.erb 文件,它无法识别使用“md:”响应实用程序的类更改。如果我使用 Chrome 开发工具检查元素,它根本不会列出 @media 类。 “md:”类显示在元素的类中,但它们没有在开发工具的样式部分中列出,并且它们不起作用。有时会发生的另一件奇怪的事情是,这些响应式类实用程序有时会起作用,有时却不起作用。其他时候,它们会起作用,如果我更改响应类实用程序中的值并重新加载页面,它就会停止工作。

我注意到的另一个奇怪行为是一些 Tailwind 类不起作用。我在类中有一个带有“border-4”的元素,它将边框宽度设置为 4px。它作为 Rails 部分工作正常,但是当我使用 ViewComponent 类渲染它时它停止工作。如果我出于某种原因将其更改为“border-2”,则该特定组件确实开始在视图组件中工作。离奇。

【问题讨论】:

    标签: ruby-on-rails ruby responsive-design tailwind-css view-components


    【解决方案1】:

    好吧,多亏了这个 reddit 帖子,我才弄明白:Bug related to view components and tailwind。我会把这个留给有同样问题的人。在 Tailwind 的配置文件 tailwind.config.js 中,需要将 ./app/components 目录添加到 content: 下的目录数组中,添加后,一切都开始正常工作。

    【讨论】:

      【解决方案2】:

      好面对同样的问题。在 tailwind.config.js 中添加以下行到您的内容中。

      content: [
        './app/components/**/*.{erb,html}',
      ],
      

      【讨论】:

        猜你喜欢
        • 2022-01-20
        • 2017-03-03
        • 1970-01-01
        • 2022-11-18
        • 2021-09-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多