【问题标题】:React component event handler - can't get access to eventReact 组件事件处理程序 - 无法访问事件
【发布时间】:2016-06-09 05:45:25
【问题描述】:

这是一个基本的 JavaScript 问题,但还是让我在谷歌上搜索了一段时间。基于this article,下面的代码应该可以工作,但是我在saveBubble 中得到event.target is not a function 错误。当我在调试器中尝试event 时,错误显示为Uncaught: illegal accessarguments数组有需要的事件,但是为什么我调用event时它不起作用?

export default class Bubble extends Component {
  saveBubble(event) {
    Bubbles.insert({
      text: event.target.attr('value') // <- throws an error here
    })
  }

  body() {
    const { text } = this.props.bubble;

    if (text) {
      return text;
    }
    else {
      return (
        <input type='text' onBlur={ this.saveBubble.bind(this) }/>
      )
    }
  }

  render() {
    return (
      <div className='bubble-wrapper'>
        <div className='body'>
          { this.body() }
        </div>
      </div>
    );
  }
}

【问题讨论】:

  • 我的猜测是body() 函数中的this 并不是你想象的那样。尝试将其绑定到您的render()
  • @ivarni 在saveBubblebody 中,this 是 Bubble 对象
  • 我还注意到,如果我要求事件,它会给我“未捕获的非法访问”错误。但如果我要求 event.target 它似乎工作。

标签: javascript mongodb meteor reactjs event-handling


【解决方案1】:

我想你可能想要event.target.value 而不是event.target.attr('value')。这将为您提供输入元素中的当前值,如 react docs 中所述。

我的猜测是您实际上收到了 event.target.attr is not a function 作为错误消息,因为 dom 元素(如 event.target)没有此方法,例如 jquery 对象。

为了更清楚一点,我相信这应该适合你:

saveBubble(event) {
  Bubbles.insert({
    text: event.target.value
  })
}

【讨论】:

  • 你是对的。深夜,我误读了错误。我仍然对为什么它在控制台中向我抛出非法访问错误感到困惑。
  • 是的,我自己以前从未见过那个。快速的谷歌显示至少还有一些人对此感到困惑,所以你并不孤单。
猜你喜欢
  • 2019-04-26
  • 2018-01-25
  • 2017-01-08
  • 2010-12-06
  • 1970-01-01
  • 2015-06-17
  • 2020-09-12
相关资源
最近更新 更多