這是我第一次進入React。React複選框ajax put request中的布爾值/ Rails
我正在使用兩次複選框組件。這是父組件:
var SearchItem = React.createClass({
getInitialState: function(){
return { data: [] };
},
render: function(){
return <div className='searchItem'>
<p>{this.props.data.date}</p>
<a href={this.props.data.url} target='_blank' {this.props.data.title}</a>
<p>{this.props.data.company}</p>
<p>{this.props.data.description}</p>
<form>
<CheckBox value = {this.props.data.saved} id = {this.props.data.id} text = 'Save' />
<CheckBox value = {this.props.data.applied} id = {this.props.data.id} text = 'Applied' />
</form>
</div>
}
});
我想在這裏做的就是讓一個ajax放置請求,通過爲保存或應用一個布爾值,根據上下文。這是CheckBox組件:
var CheckBox = React.createClass({
getInitialState: function(){
return { data: [] }
},
handleClick: function(e){
$.ajax({
data: // not sure what to do here,
dataType: 'json',
url: '/searches/' + this.props.id + '.json',
type: 'put',
context: this,
success: function(data, status, xhr){
this.setState({
// not sure what to do here
});
}.bind(this),
error: function(xhr, status, err){
console.log("whoops, something didn't work:"),
console.log(status, err.toString());
}.bind(this)
});
},
render: function(){
var value = this.props.value;
return (
<label><input type='checkbox' className='checkBox' defaultChecked={value} onClick={this.handleClick} />{this.props.text}</label>
)
}
});
我想要的數據值,看起來像這樣:{保存:布爾}或{應用:布爾}取決於這是否是保存複選框或應用複選框。
問題:
1)不知道如何動態設置的數據值,這樣我就可以重新使用這個組件。 ('checked')?這個複選框的布爾技巧'$('input:checkbox')。is('checked')? true:false'不起作用,因爲'$('input:checkbox')'返回頁面上的每個複選框。
3)我想成功回調中的數據應該是我更新後的模型,我需要抓住我剛更新的任何屬性來設置組件的狀態。對?但是,再次,我需要確定它是哪個複選框。
編輯:
這是CheckBox組件看起來像什麼。
var CheckBox = React.createClass({
getInitialState: function(){
return { data: [] }
},
componentDidMount: function(){
this.setState({
checked: this.props.value
});
},
handleClick: function(e){
var ajaxData = {}
ajaxData[this.props.attribute] = !this.state.checked;
$.ajax({
data: ajaxData,
dataType: 'json',
url: '/searches/' + this.props.id + '.json',
type: 'put',
context: this,
success: function(data, status, xhr){
this.setState({
checked: data[this.props.attribute]
});
}.bind(this),
error: function(xhr, status, err){
console.log(status, err.toString());
}.bind(this)
});
},
render: function(){
return (
<label><input type='checkbox' checked={this.state.checked} className='checkBox' onClick={this.handleClick} />{this.props.text}</label>
)
}
});
嘿,非常感謝您的意見。但有一兩件事,它似乎並不喜歡這個功能工作: 'toggleChecked:函數(){ \t \t \t的console.log(' 狀態:」 + this.state.checked) \t \t \t this.setState( { \t \t \t \t檢查:this.state.checked \t \t \t}); \t \t \t console.log('state is now:'+ this.state.checked) \t \t}''。它爲兩者記錄相同的布爾值。 –
嘗試在'componentDidMount'和'toggleChecked'中用'isChecked'替換'checked'。我不確定是否允許使用「checked」這個詞。 – nbermudezs
檢查是允許的,但是這個setState函數沒有做它應該做的事情 –