2016-06-09 92 views
1

这是一个基本的JavaScript问题,但仍然让我搜索了一段时间。基于this article,下面的代码应该工作,但我得到event.target is not a function错误saveBubble。当我在调试器中尝试event时,错误显示为Uncaught: illegal accessarguments array有需要的事件,但为什么当我拨打event时它不工作?React组件事件处理程序 - 无法访问事件

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> 
    ); 
    } 
} 
+0

我的猜测是,'this'在'体()'函数是不是你认为它是。尝试在你的'render()'中绑定它。 – ivarni

+0

@ivarni在'saveBubble'和'body'中,'this'是Bubble对象 –

+0

我也注意到,如果我要求事件,它会给我“未捕获的非法访问”错误。但是,如果我问event.target它似乎工作。 – stealthysnacks

回答

4

我想你可能想要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 
    }) 
} 
+0

你说得对。现在已经深夜了,我误解了错误。我仍然困惑,为什么它会在控制台中抛出非法访问错误。 –

+0

是的,我从来没有见过这样的人。一个快速的谷歌显示至少有一些其他人也困惑,所以你并不孤单。 – dougshamoo