React + Map + Button不起作用

时间:2017-10-30 15:12:22

标签: javascript json reactjs dictionary

基本功能。

  1. 列印清单完成
  2. 为每个列表添加按钮完成
  3. 按钮调用特定功能。 现在工作!!!
  4.   

    感谢所有人! -   2017/10/10 - 我找到了解决方案。在const renderItems的最后,我刚刚添加了一个简单的这个并且有效。当然,我忘了在这个示例中添加this.handleClick = this.handleClick.bind(this);在构造函数上。所以现在,正在为我工​​作

    我已经对它进行了研究,我找到的最佳解决方案就在这里:但每次我尝试使用本指南时:https://reactjs.org/docs/handling-events.html

    但我总是得到错误:

      

    未捕获的TypeError:无法读取属性' handleClick'未定义的

    我无法理解为什么。我做了什么(或做错了什么)?

    
    
    import React, { Component } from 'react';
    import axios from 'axios';
    
    class myApp extends Component {
        constructor(props) {
            super(props);
            this.state = {
                repos: []
            };
            this.handleClick = this.handleClick.bind(this); // ADDED
        }
    
        componentDidMount() {
            var $this = this;
            var URL = JSON;
    
            axios.get(URL).then(function(res) {
                $this.setState({
                    repos: res.data
                });
            })
            .catch(function(e) {
                console.log("ERROR ", e);
            });
        }
    
      handleClick() {
            console.log('this is:', this);
      }
    
      render() {
          const renderItems = this.state.repos.map(function(repo, i) {
              return <li
                        key={i}>
                        <a onClick={(e) => this.handleClick(e)} >Click here!</a>
                        <span className='repoName'>
                            {repo.full_name}
                        </span>
                        <hr />
                  </li>
          }, this); // just added THIS!
    
        return (
    
            <ul>
                  {renderItems}
            </ul>
            <section className='target'>
                  Target
            </section>
        );
      }
    }
    
    export default myApp;
    &#13;
    &#13;
    &#13;

2 个答案:

答案 0 :(得分:0)

您收到一个未定义的错误,因为您的方法定义中缺少参数e。没有参数的handleClick()具有与handleClick(e)不同的标识。

在构造函数中绑定handleClickthis.handleClick = this.handleClick.bind(this);

然后将onClick道具更改为onClick={this.handleClick}。永远不要在render函数中使用箭头函数,这会在每次重新渲染时创建函数的新标识,这是不好的做法,并且随着应用程序的增长可能会导致性能问题。

您也可以使用实验public class fields syntax,然后就可以定义您的点击处理程序;

&#13;
&#13;
handleClick = (e) => {
  // Stuff
}
&#13;
&#13;
&#13;

像这样,您不需要进行任何绑定,只需将this.handleClick放入onClick道具。

答案 1 :(得分:0)

this内的(e) => this.handleClick(e)不是班级this。只需这样onClick={this.handleClick}。这样您就可以在this函数中的handleClick内点击事件。如果您想要this内的handleClick课,而不是this.handleClick.bind(this)

相关问题