2016-06-09 134 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

相關問題