Pau*_*aul 5 ruby ruby-on-rails responsive-design tailwind-css view-components
我正在使用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
Run Code Online (Sandbox Code Playgroud)
使用视图组件 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 %>
Run Code Online (Sandbox Code Playgroud)
当显示器为中等 (md) 或更大时,Tailwind 类使底部边距从 2 更改为 0。此外,当显示器为中等或更大时,提交按钮从宽度 100% 更改为宽度 fit-content。如果我使用视图目录中的部分部分的通常 Rails 渲染来渲染它,它就可以正常工作。如果我使用 ViewComponent 类渲染完全相同的 html.erb 文件,它无法识别“md:”响应实用程序的类更改。如果我使用 Chrome 开发工具来检查该元素,它根本不会列出 @media 类。“md:”类显示在元素的类中,但它们未列在开发工具的样式部分中,并且不起作用。有时会发生的另一个奇怪的事情是,这些响应类实用程序有时会起作用,有时则不起作用。其他时候,它们可以工作,如果我更改响应类实用程序中的值并重新加载页面,它就会停止工作。
我注意到的另一个奇怪的行为是一些 Tailwind 类不起作用。我在类中有一个带有“border-4”的元素,它将边框宽度设置为 4px。它作为 Rails 部分工作正常,但当我使用 ViewComponent 类渲染它时,它停止工作。如果我出于某种原因将其更改为“border-2”,那么这个特定的组件就会开始在视图组件中工作。太奇怪了。
好吧,多亏了这篇 reddit 帖子,我才弄清楚了这一点:Bug related to view Components and tailwind。我将把这个留给有同样问题的人。在 Tailwind 的配置文件中tailwind.config.js
,需要将 ./app/components 目录添加到“content:
一旦我添加它,一切就开始正常工作”下的目录数组中。
小智 5
我遇到了同样的问题。在tailwind.config.js
您的内容中添加以下行:
content: [
'./app/components/**/*.{erb,html}',
],
Run Code Online (Sandbox Code Playgroud)