我只是在开始学习时就做出反应,并立即遇到有关绑定的问题。
我总是收到“无法读取未定义的属性'onDismiss'”的错误,并且我不知道如何解决此问题。尝试了多种方法来正确绑定“ this”,但没有任何效果。
这是我的应用程序组件的完整代码:
import React, { Component } from 'react';
import './App.css';
const list = [
{
title: 'React',
url: 'https://reactjs.org/',
author: 'Jordan Walke',
num_comments: 3,
points: 4,
objectID: 0,
},
{
title: 'Redux',
url: 'https://redux.js.org/',
author: 'Dan Abramov',
num_comments: 2,
points: 5,
objectID: 1,
},
{
title: 'Reddit',
url: 'https://reddit.com/',
author: 'Crazy Guys',
num_comments: 2000,
points: 3,
objectID: 2,
},
];
class App extends Component {
constructor(props) {
super(props);
this.state = {
list: list,
list_title: 'Links',
};
this.onDismiss = this.onDismiss.bind(this);
}
onDismiss(id) {
console.log(id)
//const isNotId = item => item.objectID !== id;
//const updateList = this.state.list.filter(isNotId);
}
render() {
return (
<div className="App">
<h2>{this.state.list_title}</h2>
{this.state.list.map(function(item) {
return (
<div key={item.objectID}>
<span>
<a href={item.url}>{item.title}</a>
</span>
<span>
{item.author}
</span>
<span>
{item.num_comments}
</span>
<span>
{item.points}
</span>
<span>
<button
onClick={() =>
this.onDismiss(item.objectID)}
type="button"
>
Dismiss
</button>
</span>
</div>
);
})}
</div>
);
}
}
export default App;
答案 0 :(得分:0)
之所以发生这种情况,是因为您没有将函数绑定到onClick事件处理程序。
onClick={this.onDismiss.bind(this,item.objectID)}
答案 1 :(得分:0)
更改
${a[@]}
到
<h2>{this.state.list_title}</h2>
{this.state.list.map(function(item) { ... }}