Reactを使い始めたばかりで、子コンポーネント内の入力の入力値を集めるのに問題があります。基本的には、私が作成している大きなフォームのためのさまざまなコンポーネントを作成していますが、包括的なコンポーネントでは、データを呼び出すオブジェクトの子にあるすべての入力値を収集し、その収集した入力をPOST AJAXリクエスト(私が最後に作成したコンポーネントの例を見ることができます)。私は、コンポーネントの内部にあるときに値を簡単に引き出すことができますが、私が理解していない親コンポーネントからそれらを引き出します。Reactの子コンポーネントから値を取得する方法
ありがとうございます。 Reactで今すぐ痛みを経験するだけで、これをどのように構造化するかについての推奨事項は、私はすべての耳です!ここで
は私のコンポーネントは以下のとおりです。
コンポーネント1
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
コンポーネント2
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
@luke jsfiddledコードを試すことができますか? – Zakaria