【问题标题】:attach event listener within a loop in react在反应循环中附加事件侦听器
【发布时间】:2017-10-07 09:04:21
【问题描述】:

这是我的代码

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 的每个元素中添加一个 onclick 事件。但是这段代码对我不起作用。问题是当我点击&lt;li&gt; 元素时,它会给出loadsourcecontent 未定义错误。

在此先感谢,对我的英语感到抱歉

【问题讨论】:

标签: javascript arrays reactjs for-loop


【解决方案1】:

您需要绑定renderSource,因为 this 上下文不属于该类。

constructor(props) {
    super(props);

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

或使用 es6 箭头

【讨论】:

  • @Sourav 我会将这个renderSource 调用拆分到另一个类,而不是把它放在这个类的函数中。例如{ this.state.source.slice(0, 10).map(data =&gt; &lt;SourceListItem data={data} /&gt;) },因为它可重复使用且更清晰。
猜你喜欢
  • 1970-01-01
  • 2016-03-01
  • 2012-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多