我在我的一个React类中操作回调函数时遇到问题。我基本上是在点击时调用checkSource
,如果符合特定要求,我想调用handleSubmitClick
。我觉得这与我打电话this.handleSubmitClick
有关,但我不明白。我的理解是this
指的是我创建的组件对象。如果是这种情况,不应该只调用该函数并执行吗?
完整的组件在这里:
var React = require('react');
module.exports = React.createClass({
getInitialState: function() {
return {
text: ''
}
},
handleTextInput: function(event){
this.setState({text: event.target.value})
},
checkSource: function(){
var clientId = 'xxxx';
var resolve = 'http://api.soundcloud.com/resolve?url=';
$.get(resolve + this.state.text + '&client_id=' + clientId, function(data) {
$.get('http://api.soundcloud.com/users/' + data.user.id + '/?client_id=' + clientId, function(data) {
if(data.followers_count < 3000) {
console.log("handleSubmitClick now");
this.handleSubmitClick();
} else {
return false;
}
});
});
},
handleSubmitClick: function() {
console.log('handleSubmitClick going')
console.log(this.state.text)
var linkStore = this.props.linkStore
linkStore.push(this.state.text)
this.setState({text: ''})
this.props.handleListSubmitClick(linkStore)
console.log(this.props.linkStore)
},
render: function() {
return <div className="row">
<div className="col-md-8 col-md-offset-2">
<div className="text-center">
<h1>Soundcloud3k</h1>
</div>
<div className="input-group">
<input
onChange = {this.handleTextInput}
type="text"
className="form-control"
placeholder="Search fr..."
value={this.state.text} />
<span className="input-group-btn">
<button
onClick={this.checkSource}
className="btn btn-default"
type="button">Submit!</button>
</span>
</div>
</div>
</div>
}
});
这是checkSource
调用
checkSource
功能的控制台日志按预期工作,但我无法让handleSubmitClick
做任何事情。我在控制台中没有收到任何错误或任何错误。有什么想法吗?
答案 0 :(得分:1)
在$.get
回调this
未引用您的组件时,您应为每次回调设置this
。另外,ajax回调中的return false
没有意义,所以你可以删除它
checkSource: function(){
var clientId = 'xxxx';
var resolve = 'http://api.soundcloud.com/resolve?url=';
$.get(resolve + this.state.text + '&client_id=' + clientId, function(data) {
$.get('http://api.soundcloud.com/users/' + data.user.id + '/?client_id=' + clientId, function(data) {
if(data.followers_count < 3000) {
this.handleSubmitClick();
}
}.bind(this));
}.bind(this));
},