2017-10-07 92 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 =>)}'因为它可以重复使用和清晰。 –

相关问题