Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 如何从React中的子组件获取值_Jquery_Ajax_Reactjs - Fatal编程技术网

Jquery 如何从React中的子组件获取值

Jquery 如何从React中的子组件获取值,jquery,ajax,reactjs,Jquery,Ajax,Reactjs,所以我刚刚开始使用React,在子组件中收集输入值时遇到了问题。基本上,我正在为我正在制作的一个大型表单创建不同的组件,然后在包含的组件中,我希望收集我正在调用数据的对象中子对象的所有输入值,然后将收集到的输入发送到一个POST AJAX请求中(您可以在我制作的上一个组件中看到一个示例)。当我在组件内部时,我可以很容易地提取这些值,但是从父组件中提取它们我还没有弄清楚 提前谢谢。现在,我正与React一起经历这些痛苦,因此,关于如何更好地构建此结构的任何建议,我都洗耳恭听 以下是我的组件: 第一

所以我刚刚开始使用React,在子组件中收集输入值时遇到了问题。基本上,我正在为我正在制作的一个大型表单创建不同的组件,然后在包含的组件中,我希望收集我正在调用数据的对象中子对象的所有输入值,然后将收集到的输入发送到一个POST AJAX请求中(您可以在我制作的上一个组件中看到一个示例)。当我在组件内部时,我可以很容易地提取这些值,但是从父组件中提取它们我还没有弄清楚

提前谢谢。现在,我正与React一起经历这些痛苦,因此,关于如何更好地构建此结构的任何建议,我都洗耳恭听

以下是我的组件:

第一部分

var StepOne = React.createClass({
  getInitialState: function() {
    return {title: '', address: '', location: ''};
  },
  titleChange: function(e) {
    this.setState({title: e.target.value});
  },
  addressChange: function(e) {
   this.setState({address: e.target.value});
  },
  locationChange: function(e) {
    this.setState({location: e.target.value});
  },
  render: function() {
    return (
      <div className="stepOne">
        <ul>
          <li>
            <label>Title</label>
            <input type="text" value={this.state.title} onChange={this.titleChange} />
          </li>
          <li>
            <label>Address</label>
            <input type="text" value={this.state.address} onChange={this.addressChange} />
          </li>
          <li>
            <label>Location</label>
            <input id="location" type="text" value={this.state.location} onChange={this.locationChange} />
          </li>
        </ul>
      </div>
    );
  }, // render
}); // end of component
var StepOne=React.createClass({
getInitialState:函数(){
返回{标题:'',地址:'',位置:'};
},
标题更改:功能(e){
this.setState({title:e.target.value});
},
地址更改:功能(e){
this.setState({地址:e.target.value});
},
位置更改:功能(e){
this.setState({location:e.target.value});
},
render:function(){
返回(
  • 标题
  • 地址
  • 位置
); },//渲染 }); // 部件末端
第二部分

var StepTwo = React.createClass({
  getInitialState: function() {
    return {name: '', quantity: '', price: ''}
  },
  nameChange: function(e) {
    this.setState({name: e.target.value});
  },
  quantityChange: function(e) {
    this.setState({quantity: e.target.value});
  },
  priceChange: function(e) {
    this.setState({price: e.target.value});
  },
  render: function() {
    return (
      <div>
      <div className="name-section">
        <div className="add">
          <ul>
            <li>
              <label>Ticket Name</label>
              <input id="name" type="text" value={this.state.ticket_name} onChange={this.nameChange} />
            </li>
            <li>
              <label>Quantity Available</label>
              <input id="quantity" type="number" value={this.state.quantity} onChange={this.quantityChange} />
            </li>
            <li>
              <label>Price</label>
              <input id="price" type="number" value={this.state.price} onChange={this.priceChange} />
            </li>
          </ul>
        </div>
      </div>
      </div>
    );
  }
});
var step2=React.createClass({
getInitialState:函数(){
返回{名称:'',数量:'',价格:'}
},
名称更改:功能(e){
this.setState({name:e.target.value});
},
数量变化:函数(e){
this.setState({quantity:e.target.value});
},
价格变化:功能(e){
this.setState({price:e.target.value});
},
render:function(){
返回(
  • 票名
  • 可用数量
  • 价格
); } });
收集数据并提交ajax请求的最终组件

EventCreation = React.createClass({
 getInitialState: function(){
  return {}
},
submit: function (e){
  var self

  e.preventDefault()
  self = this

  var data = {
    // I want to be able to collect the values into this object then send it in the ajax request. I thought this sort of thing would work below:
    title: this.state.title,
  }

  // Submit form via jQuery/AJAX
  $.ajax({
    type: 'POST',
    url: '/some/url',
    data: data
  })
  .done(function(data) {
    self.clearForm()
  })
  .fail(function(jqXhr) {
    console.log('failed to register');
  });
},
render: function() {
    return(
      <form>
        <StepOne />
        <StepTwo />
        // submit button here
      </form>
    );
  }
});
EventCreation=React.createClass({
getInitialState:函数(){
返回{}
},
提交:职能(e){
var self
e、 预防默认值()
self=这个
风险值数据={
//我希望能够将值收集到这个对象中,然后在ajax请求中发送它。我认为这类事情将在以下方面起作用:
标题:this.state.title,
}
//通过jQuery/AJAX提交表单
$.ajax({
键入:“POST”,
url:“/some/url”,
数据:数据
})
.完成(功能(数据){
self.clearForm()
})
.失败(功能(jqXhr){
console.log('注册失败');
});
},
render:function(){
返回(
//提交按钮在这里
);
}
});

首先,您需要设置一些。它将允许您轻松访问一些DOM元素。 例:

编辑1: 您还必须向组件添加
ref

render:function(){ 返回( //提交按钮在这里 ); } 然后,访问您的元素:

var data = {
    name: this.refs.steOneRef.refs.stepOneName.value
    }

ant对我来说似乎没问题。

在子组件中定义返回所需数据的方法,然后在呈现子组件时在父组件中定义引用,以便稍后在要检索所需数据时可以在子组件上调用这些方法

StepOne = React.createClass({
    getData: function() {
        return this.state;
    }
});

StepTwo = React.createClass({
    getData: function() {
        return this.state;
    }
});

EventCreation = React.createClass({
    submit: function() {
        var data = Object.assign(
            {},
            this._stepOne.getData(),
            this._stepTwo.getData()
        );

        // ... do AJAX
    },

    render: function() {
        return (
            <StepOne ref={(ref) => this._stepOne = ref} />
            <StepTwo ref={(ref) => this._stepTwo = ref} />
        );
    }
});
StepOne=React.createClass({
getData:function(){
返回此.state;
}
});
第二步=React.createClass({
getData:function(){
返回此.state;
}
});
EventCreation=React.createClass({
提交:函数(){
var data=Object.assign(
{},
这是。_stepOne.getData(),
这是。_step2.getData()
);
//…做AJAX
},
render:function(){
返回(
这个。_stepOne=ref}/>
这个。_step2=ref}/>
);
}
});

一般来说,您需要将一个函数作为道具从父级传递给子级。当孩子们的数据发生变化时,他们将调用该函数作为回调函数

这样做的最大优点是让父组件跟踪应用程序中的所有状态,并将状态片段作为道具传递给子组件,而不是让每个组件跟踪自己的内部状态。()

您的组件可能如下所示:

var StepOne = React.createClass({
  handleOnChange: function(e){
     this.props.handleChange(e.target.name, e.target.value);
  },      
  render: function() {
    return (
      <div className="stepOne">
        <ul>
          <li>
            <label>Title</label>
            <input type="text" name="title" value={this.props.title} onChange={this.handleChange} />
          </li>
          ...
        </ul>
      </div>
    );
  }, // render
}); // end of component

EventCreation = React.createClass({
 getInitialState: function(){
  return {}
},
handleChange: function(name, value){
    var tmp = {};
    tmp[name] = value;
    this.setState(tmp);
},
submit: function (e){
  var self

  e.preventDefault()
  self = this

  var data = {
    // I want to be able to collect the values into this object then send it in the ajax request. I thought this sort of thing would work below:
    title: this.state.title,
  }

  // Submit form via jQuery/AJAX
  $.ajax({
    type: 'POST',
    url: '/some/url',
    data: data
  })
  .done(function(data) {
    self.clearForm()
  })
  .fail(function(jqXhr) {
    console.log('failed to register');
  });
},
render: function() {
    return(
      <form>
        <StepOne handleChange={this.handleChange.bind(this)} title={this.state.title} .../>
        <StepTwo handleChange={this.handleChange.bind(this)} ... />
        // submit button here
      </form>
    );
  }
});
var StepOne=React.createClass({
更改:功能(e){
this.props.handleChange(e.target.name,e.target.value);
},      
render:function(){
返回(
  • 标题
  • ...
); },//渲染 }); // 部件末端 EventCreation=React.createClass({ getInitialState:函数(){ 返回{} }, handleChange:函数(名称、值){ var tmp={}; tmp[name]=值; 本.设置状态(tmp); }, 提交:职能(e){ var self e、 预防默认值() self=这个 风险值数据={ //我希望能够将值收集到这个对象中,然后在ajax请求中发送它。我认为这类事情将在以下方面起作用: 标题:this.state.title, } //通过jQuery/AJAX提交表单 $.ajax({ 键入:“POST”, url:“/some/url”, 数据:数据 }) .完成(功能(数据){ self.clearForm() }) .失败(功能(jqXhr){ console.log('注册失败'); }); }, render:function(){ 返回( //提交按钮在这里 ); } });
这里有一个稍微松散耦合的解决方案。这取决于您为每个元素设置
id
。基本上你所做的是ca
StepOne = React.createClass({
    getData: function() {
        return this.state;
    }
});

StepTwo = React.createClass({
    getData: function() {
        return this.state;
    }
});

EventCreation = React.createClass({
    submit: function() {
        var data = Object.assign(
            {},
            this._stepOne.getData(),
            this._stepTwo.getData()
        );

        // ... do AJAX
    },

    render: function() {
        return (
            <StepOne ref={(ref) => this._stepOne = ref} />
            <StepTwo ref={(ref) => this._stepTwo = ref} />
        );
    }
});
var StepOne = React.createClass({
  handleOnChange: function(e){
     this.props.handleChange(e.target.name, e.target.value);
  },      
  render: function() {
    return (
      <div className="stepOne">
        <ul>
          <li>
            <label>Title</label>
            <input type="text" name="title" value={this.props.title} onChange={this.handleChange} />
          </li>
          ...
        </ul>
      </div>
    );
  }, // render
}); // end of component

EventCreation = React.createClass({
 getInitialState: function(){
  return {}
},
handleChange: function(name, value){
    var tmp = {};
    tmp[name] = value;
    this.setState(tmp);
},
submit: function (e){
  var self

  e.preventDefault()
  self = this

  var data = {
    // I want to be able to collect the values into this object then send it in the ajax request. I thought this sort of thing would work below:
    title: this.state.title,
  }

  // Submit form via jQuery/AJAX
  $.ajax({
    type: 'POST',
    url: '/some/url',
    data: data
  })
  .done(function(data) {
    self.clearForm()
  })
  .fail(function(jqXhr) {
    console.log('failed to register');
  });
},
render: function() {
    return(
      <form>
        <StepOne handleChange={this.handleChange.bind(this)} title={this.state.title} .../>
        <StepTwo handleChange={this.handleChange.bind(this)} ... />
        // submit button here
      </form>
    );
  }
});
var StepOne = React.createClass({
  getInitialState: function() {
    return {title: '', address: '', location: ''};
  },
  _onChange(e) {
    // set your state if needed

    // call the parent function
    this.props.onChange(
        e.target.id,
        e.target.value
    )
  },
  render: function() {
    return (
      <div className="stepOne">
        <ul>
          <li>
            <label>Title</label>
            <input id="title" type="text" value={this.state.title} onChange={this._onChange.bind(this)} />
          </li>
          <li>
            <label>Address</label>
            <input id="address" type="text" value={this.state.address} onChange={this._onChange.bind(this)} />
          </li>
          <li>
            <label>Location</label>
            <input id="location" type="text" value={this.state.location} onChange={this._onChange.bind(this)} />
          </li>
        </ul>
      </div>
    );
  }, // render
}); // end of component

var StepTwo = React.createClass({
  getInitialState: function() {
    return {name: '', quantity: '', price: ''}
  },
  _onChange(e) {
    // set your state if needed

    // call the parent function
    this.props.onChange(
        e.target.id,
        e.target.value
    )
  },
  render: function() {
    return (
      <div>
      <div className="name-section">
        <div className="add">
          <ul>
            <li>
              <label>Ticket Name</label>
              <input id="name" type="text" value={this.state.ticket_name} onChange={this._onChange.bind(this)} />
            </li>
            <li>
              <label>Quantity Available</label>
              <input id="quantity" type="number" value={this.state.quantity} onChange={this._onChange.bind(this)} />
            </li>
            <li>
              <label>Price</label>
              <input id="price" type="number" value={this.state.price} onChange={this._onChange.bind(this)} />
            </li>
          </ul>
        </div>
      </div>
      </div>
    );
  }

  EventCreation = React.createClass({
    getInitialState: function(){
      return {}
    },
    _onChange(id, value) {
      this.formData[id] = value;
    },
    submit: function (e){
      var self

      e.preventDefault()
      self = this

      // Submit form via jQuery/AJAX
      $.ajax({
        type: 'POST',
        url: '/some/url',
        data: this.formData
      })
      .done(function(data) {
        self.clearForm()
      })
      .fail(function(jqXhr) {
        console.log('failed to register');
      });
  },
  render: function() {
      return(
        <form>
          <StepOne onChange={this.onChange.bind(this)}/>
          <StepTwo onChange={this.onChange.bind(this)}/>
          // submit button here
        </form>
      );
    }
});