簡體   English   中英

在React中使用逆數據流設置'this'

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM