我正在使用 web-packer 和 react-rails gem 来构建在线旅游应用程序。我在使用服务器端渲染的 JSX View 中使用 Rails URL helper 时遇到问题:
例如在我的 jsx View 中:
#project/app/javascript/packs/app/components/front_end/SearchTripItemComp.erb
<%= link_to "Book Now!", search_trips_path, className: 'btn btn-book' %>
运行后我有这个错误:
我能想到的解决方法是将 search_trips_path 作为 Prop 从我的 Rails View 传递给组件,或者直接使用 Rails.application.routes.url_helpers 但这非常不方便,尤其是对于那些具有许多链接的 jsx View 。
我试图查看 web-packer 文档,但似乎 gem 不支持 erb 加载器的 Rails View 助手。
请大家帮忙指教!
ps:我已经正确配置了erb webpacker loader。
最佳答案
在你的 jsx View 中试试这个:
#project/app/javascript/packs/app/components/front_end/SearchTripItemComp.erb
<%= ActionController::Base.helpers.link_to "Book Now!", Rails.application.routes.url_helpers.search_trips_path, className: 'btn btn-book' %>
使用:
Rails.application.routes.url_helpers.*_path
代替*_path
在您的 .erb 文件中, View 外适用于 url_helpers。Rails.application.routes.url_helpers.search_trips_path
If you need to generate URLs from your models or some other place, then ActionController::UrlFor is what you're looking for. Read on for an introduction. In general, this module should not be included on its own, as it is usually included by url_helpers (as in Rails.application.routes.url_helpers).
同样对于 link_to 你可以使用:
ActionController::Base.helpers.link_to
关于ruby-on-rails-5 - 如何在 Webpacker 中使用 Rails Url helper/Rails 5.1 中的 React-rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45646562/