ruby-on-rails-5 - 如何在 Webpacker 中使用 Rails Url helper/Rails 5.1 中的 React-rails

标签 ruby-on-rails-5 react-rails react-on-rails webpacker

我正在使用 web-packerreact-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' %>


运行后我有这个错误:

enter image description here

我能想到的解决方法是将 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).

ActionDispatch::Routing::UrlFor


同样对于 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/

相关文章:

ruby-on-rails - 获取字符串的特定部分

twitter-bootstrap - Sprockets::FileNotFound:找不到类型为 'bootstrap-sprockets' 的文件 'application/javascript'

javascript - React 组件正在渲染,然后消失

javascript - 在 React 中获取 Selected 选项属性

javascript - 类型错误 : Cannot read property 'userAgent' of undefined

javascript - window.location 未定义

reactjs - react : Rendering based on date order

mysql - Ruby on Rails 和查询(理解问题)

ruby-on-rails - 如何将react-rails与webpacker结合使用?

sql - Rails Postgres 查询,仅选择出现在所有具有关联的搜索参数中的项目