【发布时间】:2017-10-30 15:12:21
【问题描述】:
基本功能。
- 打印列表完成
- 为每个列表添加一个按钮完成
- 按钮调用特定函数。 现在工作!!!
谢谢大家! - 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) => { -
Lamba 可以引入绑定方法,这样你就不必陷入这个
this陷阱 -
我找到了解决方案。在
const renderItems的末尾,我只是添加了一个简单的this并且可以工作。当然,我忘了在这个示例中在 constructor 上添加this.handleClick = this.handleClick.bind(this);。所以现在,对我有用。
标签: javascript json reactjs dictionary