2017-10-07 132 views
0

這裏是我的代碼附加一個循環內事件偵聽器中反應

import React,{ Component } from 'react'; 
import PTSearch from 'post-api-search'; 

export default class Navbar extends Component{ 
constructor(props) { 
    super(props); 

    this.state = { 
     source: [] 
    }; 

    this.sourceSearch(); 
} 

sourceSearch() { 
    PTSearch({ 
     category: "", 
     language: "en", 
     country: '' 
    }, "sources", (sources) => { 
     this.setState({ 
      source: sources 
     }); 
    }); 
} 

loadSourceContent() { 
    alert(1); 
} 

renderSource(data){ 
    return (
     <li title={data.description} onClick={this.loadSourceContent} key={data.name}>{data.name}</li> 
    ); 
} 

render(){ 
    return (
     <div> 
      <button id="menu-toggle" className="menu-toggle"><span>Menu</span></button> 
      <div id="theSidebar" className="sidebar"> 
       <button className="close-button fa fa-fw fa-close"></button> 
       <div> 
        <img src="https://vignette.wikia.nocookie.net/clonewarsadventurescharacter/images/8/81/Superman-logo-transparent.png/revision/latest?cb=20131006162105" /> 
       </div> 
       <ul className="source-list"> 
        { this.state.source.slice(0, 10).map(this.renderSource) } 
       </ul> 
      </div> 
     </div> 
    ); 
}; 

}

我想在這個代碼不爲我工作的li.But的每個元素添加一個onclick事件。問題是,當我點擊<li>元素,它給loadsourcecontent未定義的錯誤。

在此先感謝和抱歉,我的英語

+0

[onClick事件在React.js結合](的可能的複製https://stackoverflow.com/questions/27397266/onclick-event-binding-in-react-js ) – Andreas

回答

0

您需要綁定renderSource因爲這種情況下是類的不是。

constructor(props) { 
    super(props); 

    this.state = { 
     source: [] 
    }; 
    this.renderSource = this.renderSource.bind(this); 
    this.sourceSearch(); 
} 

或使用ES6箭頭

+0

謝謝,夥計。現在工作正常。 – Sourav

+0

@Sourav我將這個'renderSource'調用拆分成另一個類,而不是將它放在這個類的函數中。 E.G'{this.state.source.slice(0,10).map(data =>)}'因爲它可以重複使用和清晰。 –

相關問題