简体   繁体   English

在React中使用逆数据流设置'this'

[英]Setting 'this' in React with Inverse Data Flow

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 . 我有一个PostMain组件,该组件将功能向下传递到子组件PostForm On the AJAX success function of the callback I pass in the returned object and call this.props.addPost(data.title) function. 在回调的AJAX成功函数上,我传入返回的对象并调用this.props.addPost(data.title)函数。

I am wonderding how you can set the context of this on the function? 我wonderding如何设置的情况下this在功能上? I then call this.setState in the parent component but setState is not defined because I haven't set the context of this . 然后,我在父组件中调用this.setState ,但是未定义setState因为我尚未设置this的上下文。 Please see code below: Thank you in advance. 请参见下面的代码:提前谢谢。

This is the parent PostMain component: 这是父PostMain组件:

 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: 这是子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)
    });
  }

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)} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM