在 Rails 應用程式中新增一個簡單的反應元件(用 ruby 編寫)

  1. 將 hyperloop gem 新增到 rails(4.0 - 5.1)Gemfile 中

  2. bundle install

  3. 將 hyperloop 清單新增到 application.js 檔案中:

    // app/assets/javascripts/application.js
    ...
    //= hyperloop-loader
    
  4. 建立你的 react 元件,並將它們放在 hyperloop/components 目錄中

    # app/hyperloop/components/hello_world.rb
    class HelloWorld < Hyperloop::Component
      after_mount do
        every(1.second) { mutate.current_time(Time.now) }
      end
      render do
        "Hello World!  The time is now: #{state.current_time}"
      end
    end
    
  5. 元件就像檢視一樣。它們在控制器中使用 render_component 方法掛載

    # somewhere in a controller:
      ...
      def hello_world
        render_component # renders HelloWorld based on method name
      end