[英]Setting 'this' in React with Inverse Data Flow
我想知道是否可以在这个问题上帮助我? 我有一个PostMain
组件,该组件将功能向下传递到子组件PostForm
。 在回调的AJAX成功函数上,我传入返回的对象并调用this.props.addPost(data.title)
函数。
我wonderding如何设置的情况下this
在功能上? 然后,我在父组件中调用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>
)
}
}
这是子PostForm
组件:
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)
});
}
只需将函数绑定到您的组件,然后再将其传递给孩子。
<PostForm addPost={this.addPost} posts={this.state.posts} />
应该
<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)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.