如何使用React的ref来检索表单元素?

时间:2016-06-26 06:57:03

标签: ruby-on-rails reactjs ruby-on-rails-5

我的任务是上传图片并更新用户表,而不刷新页面。我的搜索建议使用refs抓取表单元素,但我在控制台中获取:

  

ActionController :: ParameterMissing(param丢失或值为空:user):

     

app / controllers / users_controller.rb:8:user_params' app/controllers/users_controller.rb:3:in更新'

路线:

Rails.application.routes.draw do
  get 'welcome/index'

  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  root 'welcome#index'
  resources :users do
    member do
      post 'upload' => 'users#update'
    end
  end
end

该应用:

var User = React.createClass({

  componentDidMount: function(){
    // Trying so see what this shows in the browser console
    var foo = $(this.refs.myForm).elements;
    console.log(foo);
  }.bind(this),

  onUpload: function(){
    var formData = $(this.refs.myForm).serialize();
    $.ajax({
       url: '/users/1/upload',
       type: 'POST',
       data: formData,
       async: false,
       cache: false,
       contentType: false,
       processData: false,
       success: function (data) {
           console.log("success: " + data);
       },
       error: function () {
           alert("error in ajax form submission");
       }
    });
  },
  render: function(){
    return(
      <div>
        <form ref="myForm" remote="true">
          <input type="file" name="user[avatar]" />
        </form>
         {/* Placing the button outside the form prevents a refresh */}
        <button className="button" onClick={this.onUpload}>Upload</button>
      </div>
    )
  }
});
module.exports = User;

用户控制器:

class UsersController < ApplicationController
  def update
    User.find(1).update_attributes(user_params)
  end

  private
    def user_params
      params.require(:user).permit(:avatar)
    end
end

我已经看到,在网络上,其他人使用this.refs.myForm.elements所以这里有什么问题?

2 个答案:

答案 0 :(得分:0)

更改

BaseViewController

<input type="file" name="user[avatar]" />

更改

<input type="file" name="user" />

remove bind(this) from componentDidMount

  componentDidMount: function(){
    // Trying so see what this shows in the browser console
    var foo = $(this.refs.myForm).elements;
    console.log(foo);
  }.bind(this),

答案 1 :(得分:0)

确定。感谢您的帮助,Piyush,您的时间和精力。你给了我搜索什么的线索。 Moh Arjmandi的答案是here

重新连接我的功能:

onUpload: function(){
    var fd = $(this.refs.myForm).context;
    var formData = new FormData(fd);
    $.ajax({
       url: '/users/1/upload',
       type: 'POST',
       data: formData,
       async: false,
       cache: false,
       contentType: false,
       processData: false,
       success: function (data) {
           console.log("success: " + data);
       },
       error: function () {
           alert("error in ajax form submission");
       }
    });
  },

引用Moh

  如果你想用post方法发送一个表单,那么

serialize()不是一个好主意。例如,如果你想通过ajax传递一个文件,那就不行了。

完整的应用here