所以我刚刚开始使用 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>
);
}
});
原文由 luke 发布,翻译遵循 CC BY-SA 4.0 许可协议
在子组件中定义返回所需数据的方法,然后在渲染子组件时在父组件中定义 refs,以便稍后当您想要检索所需数据时可以在子组件上调用这些方法。