【问题标题】:React + Map + Button doesn't work [duplicate]React + Map + Button 不起作用[重复]
【发布时间】:2017-10-30 15:12:21
【问题描述】:

基本功能。

  1. 打印列表完成
  2. 为每个列表添加一个按钮完成
  3. 按钮调用特定函数。 现在工作!!!

谢谢大家! - 2017 年 10 月 30 日 - 我找到了解决方案。在 const renderItems 的末尾,我只是添加了一个简单的 this 并且可以工作。当然,我忘了在这个示例中添加 this.handleClick = this.handleClick.bind(this);在构造函数上。所以现在,对我有用

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

但我总是得到错误:

未捕获的类型错误:无法读取未定义的属性“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;

【问题讨论】:

  • 这是一个非常常见的“上下文问题”,您需要将此(类上下文)与地图回调函数绑定或使用箭头函数,如下所示:this.state.repos.map((repo, i) =&gt; {
  • Lamba 可以引入绑定方法,这样你就不必陷入这个this 陷阱
  • 我找到了解决方案。在const renderItems 的末尾,我只是添加了一个简单的this 并且可以工作。当然,我忘了在这个示例中在 constructor 上添加 this.handleClick = this.handleClick.bind(this);。所以现在,对我有用。

标签: javascript json reactjs dictionary


【解决方案1】:

(e) =&gt; this.handleClick(e) 中的 this 不是 this 类。只需这样做onClick={this.handleClick}。这样您将在handleClick 函数中的this 内有点击事件。如果你想在handleClick 里面上课this,那么就去做this.handleClick.bind(this)

【讨论】:

    【解决方案2】:

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

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

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

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

    handleClick = (e) => {
      // Stuff
    }

    像这样,你不需要做任何绑定,你可以把this.handleClick放在你的onClick属性中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-26
      • 2019-01-12
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      • 2020-07-12
      相关资源
      最近更新 更多