得到这个错误:
ViewComponent::TemplateError in Welcome#show
Couldn't find a template file or inline render method for FaqComponent::QuestionComponent.
有点永远被这个问题困住了,不知道如何解决它。试图呈现一个简单的组件使用view_component
宝石。
# app/components/faq_component.rb
class FaqComponent < ViewComponent::Base
renders_many :questions, "QuestionComponent"
class QuestionComponent < ViewComponent::Base
attr_reader :question
def initialize(question: "")
@question = question
end
end
end
现在,模板文件看起来像:文件位置:app/components/faq_component/faq_component.html.erb
<%= content_tag :div, class: "c-faq", data: { controller: "faq" } do %>
<%= content_tag :div, class: "c-card" do %>
<% questions.each do |q| %>
<%= content_tag :div, class: "c-card__section" do %>
<button class="c-faq__question" data-faq-target="question">
<%= q.question %>
<%= icon("arrow-expand", classes: "u-m-0", size: 12) %>
</button>
<div class="c-faq__answer">
<%= q %> <!- IT'S GETTING ERROR HERE ->
</div>
<% end %>
<% end %>
<% end %>
<% end %>
最后尝试在这里render
:
<div class="l-container u-mb-xxl u-xs-mb-l">
<div class="l-row">
<div class="l-col-xs-26 l-col-md-24 l-col-md-offset-1">
<h3 class="u-mb-s">Common Questions</h3>
<%= render(FaqComponent.new) do |faq| %>
<% faq.question(question: "What is ViewComponent?") do %>
<p>View component is a pain because it's not working or because I'm using it for the very first time!</p>
<% end %>
<% end %>
</div>
</div>
</div>
任何帮助将非常感激!:弓
看起来你是从错误的类继承类QuestionComponent
,尝试从ViewComponent::Base
继承它
# app/components/faq_component.rb
class FaqComponent < ViewComponent::Base
renders_many :questions, "QuestionComponent"
class QuestionComponent < ViewComponent::Base
attr_reader :question
def initialize(question: "")
@question = question
end
end
end
必须为嵌套在FaqComponent
中的QuestionComponent
定义一个模板或call method
,这就是你错误的来源。
这就是为什么它在<%= q %>
失败,它试图渲染QuestionComponent
。如果您添加app/components/faq_component/question_component.html.erb
文件,可能会解决这个问题。
维护者在这里回复。干杯!