簡體   English   中英

從render方法中的嵌套函數中反映調用組件的方法

[英]React call component's method from nested function in render method

我想在onCLick上調用updateCurrentThread方法,但是我遇到了以下錯誤:

未捕獲的TypeError:無法讀取未定義的屬性“updateCurrentThread”

updateCurrentThread: function(thread) {
  this.setState({
  currentThread: thread
 }).bind(this);
},


render: function () {
  var threads = this.state.data.map(function (thread) {
    var boundClick = this.updateCurrentThread.bind(this, i);
    let time = getThreadDate(thread.timestamp);
    return (
      <div className="row thread" key={thread.threadID}>
        <ThreadParticipants onClick={boundClick} key={i} className="small-2 small-centered columns" ids={thread.participantIDs}/>
      </div>
  );
})

函數內部的this作用域是函數,而不是組件。 如果您能夠使用詞匯范圍的ES6箭頭函數,那么您當前的方法將起作用。 前箭頭的功能,人們會保存組件this一個變量(例如var self = this ),然后self.updateCurrentThread

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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