I wondered if you could help me on this problem if possible? I have a PostMain
component which passes a function down into the child component PostForm
. On the AJAX success function of the callback I pass in the returned object and call this.props.addPost(data.title)
function.
I am wonderding how you can set the context of this
on the function? I then call this.setState
in the parent component but setState
is not defined because I haven't set the context of this
. Please see code below: Thank you in advance.
This is the parent PostMain
component:
addPost(post) {
this.setState({posts: post.title})
}
render() {
return (
<div>
<h1>Main form</h1>
<PostForm addPost={this.addPost} posts={this.state.posts} />
</div>
)
}
}
This is the child PostForm
component:
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)
});
}
Just bind the function to your component before you pass it to your child.
<PostForm addPost={this.addPost} posts={this.state.posts} />
should be
<PostForm addPost={this.addPost.bind(this)} posts={this.state.posts} />
另一种选择是在onClick中设置状态内联:
<PostForm addPost={this.addPost} posts={()=> this.setState({posts: post.title})} />
您也应该将其绑定到组件中
addPost ={ this.addPost.bind(this)}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.