所以我刚刚开始使用 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 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>
);
}
});
收集数据并提交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>
);
}
});