【问题标题】:React call component's method from nested function in render method从渲染方法中的嵌套函数反应调用组件的方法
【发布时间】:2016-02-21 23:10:24
【问题描述】:

我想调用方法 updateCurrentThread onCLick,但是我收到以下错误:

未捕获的类型错误:无法读取未定义的属性“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 指的是作为map 的第一个参数的函数的函数范围。使用thread =&gt; { } 而不是function(){}
  • 正在调查... :)
  • 这是我的整个反应文件:pastebin.com/Qs1uGiRk
  • 我刚刚在地图闭包中回答了一个与此引用相关的类似问题;这个答案应该可以帮助你stackoverflow.com/a/35534177/4206756

标签: javascript reactjs react-native react-jsx


【解决方案1】:

函数内的this 的作用域是函数,而不是组件。如果您能够使用词法范围的 ES6 箭头函数,那么您当前的方法将起作用。在箭头函数之前,人们会将组件this 存储在一个变量中(例如var self = this),然后是self.updateCurrentThread

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-29
    • 1970-01-01
    • 2023-02-16
    • 2017-07-19
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    相关资源
    最近更新 更多