传递多个参数以在reactjs中起作用

时间:2017-02-06 08:26:23

标签: javascript reactjs

我在节点server.js艺术家对象中有一个json文件作为状态

{
  id: 1,
  name: "name_test1",
  email: "test1@test1.pl",
  pass: "pass_test1",
},

我创建了一个表单来向对象添加新的艺术家:

<div className="form-group">
    <label for="exampleInputName2">Name</label>
    <input
        name="name" className="form-control" placeholder="name" value={this.state.name}
        onChange={this.onInputChange.bind(this, 'name')} />
  </div>
  <div className="form-group">
    <label for="exampleInputEmail2">Email</label>
    <input
        type="email" className="form-control" placeholder="email" value2={this.state.email}
        onChange={this.onInputChange.bind(this, 'email')}  />

</div>
<div className="form-group">
  <label for="exampleInputEmail2">Password</label>
  <input
      type="password" className="form-control"  placeholder="password" value3={this.state.password}
      onChange={this.onInputChange.bind(this, 'password')}  />

<button type="submit" className="btn btn-default" onClick={this.onClick}>Add Artist</button><br/><br/>

我想将输入(名称,电子邮件,密码)中的数据发送到我的onClick函数,该函数如下所示:

   onInputChange: function(name, e) {
    var change = {};
    change[name] = e.target.value;
    this.setState(change)
  },



onClick: function() {
    if (this.state.name !== "" || this.state.email !== "" || this.state.password !=="") {
      Actions.postArtist(this.state.name);
    }
    this.setState({name: ""})
  },

但是我不知道如何将onClick函数传递给多个参数(现在我有了名字,但是也希望从我输入的电子邮件和密码中获取。

当我在我的公式上提交onClick按钮时,我的对象看起来像:

{id: 1486368952, name: "BLEH"}

我希望看起来像这样:

{id: 1486368952, name: "BLEH", email: "xxx", password: "xxx"}

我的postArtist功能如下所示:

postArtist: function(name, email, password) {

if(!this.artists) {
  this.artists = [];
}
  var artist = {
    "id": Math.floor(Date.now() / 1000),
    "name": name,
    "email": email,
    "password": password,
    // "password_conf": password_conf
  };
  this.artists.push(artist);

1 个答案:

答案 0 :(得分:0)

你可以这样写:

onClick: function() {
    if (this.state.name !== "" || this.state.email !== "" || this.state.password !=="") {
      let data = this.state;
      let obj = {name: data.name, email: data.email, password: data.password}
      Actions.postArtist(obj);
    }
    this.setState({name: ""})
  },

或者你可以传递完整状态obj,如果它只包含这3个字段,如下所示:

 onClick: function() {
      if (this.state.name !== "" || this.state.email !== "" || this.state.password !=="") {
          Actions.postArtist(this.state);
      }
      this.setState({name: ""})
  },

在postArtist方法中,将它作为这样的对象接收:

postArtist: function(data) {

  if(!this.artists) {
    this.artists = [];
  }
  var artist = {
    "id": Math.floor(Date.now() / 1000),
    "name": data.name,
    "email": data.email,
    "password": data.password,
    // "password_conf": password_conf
  };
  this.artists.push(artist);