Javascript 设置';这';与反向数据流进行交互
如果可能的话,我想知道你是否能在这个问题上帮助我?我有一个Javascript 设置';这';与反向数据流进行交互,javascript,jquery,reactjs,this,Javascript,Jquery,Reactjs,This,如果可能的话,我想知道你是否能在这个问题上帮助我?我有一个PostMain组件,它将函数向下传递到子组件PostForm。在回调的AJAX成功函数中,我传入返回的对象并调用this.props.addPost(data.title)函数 我想知道你如何在函数上设置这个的上下文?然后我在父组件中调用this.setState,但是setState没有定义,因为我没有设置this的上下文。请参阅下面的代码:提前谢谢 这是父PostMain组件: addPost(post) { this.s
PostMain
组件,它将函数向下传递到子组件PostForm
。在回调的AJAX成功函数中,我传入返回的对象并调用this.props.addPost(data.title)
函数
我想知道你如何在函数上设置这个
的上下文?然后我在父组件中调用this.setState
,但是setState
没有定义,因为我没有设置this
的上下文。请参阅下面的代码:提前谢谢
这是父PostMain
组件:
addPost(post) {
this.setState({posts: post.title})
}
render() {
return (
<div>
<h1>Main form</h1>
<PostForm addPost={this.addPost} posts={this.state.posts} />
</div>
)
}
}
addPost() {
$.ajax({
type: "POST",
url: '/posts',
dataType: 'json',
data: {
title: this.state.itemPost
},
success: function(data) {
const postTitle = data.title;
this.props.addPost(postTitle);
}.bind(this)
});
}
您还应该在组件中绑定它
addPost ={ this.addPost.bind(this)}
只需将函数绑定到组件,然后再将其传递给子组件
<PostForm addPost={this.addPost} posts={this.state.posts} />
应该是
<PostForm addPost={this.addPost.bind(this)} posts={this.state.posts} />
另一种选择是在onClick中设置内联状态:
this.setState({posts:post.title})}/>
签出