我做错了什么,特别是当我点击它给我的按钮时:未捕获的TypeError:无法读取属性' onDismiss'未定义的
何时需要将事件处理程序绑定到构造函数?
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import contacts from './contacts';
class App extends Component {
constructor(props){
super(props)
this.state = {
contacts
};
this.onDismiss = this.onDismiss.bind(this);
}
onDismiss(id) {
console.log(id)
}
render() {
return (
<div className="App">
{
this.state.contacts.map(function(contact, i){
return(
<div key={contact.id}> <br></br>
<div> First Name:</div>
<span> {contact.first_name}</span>
<div> Last Name:</div>
<span> {contact.last_name}</span>
<div> Email:</div>
<span> {contact.email}</span>
<div> <button type="button" onClick={() => this.onDismiss(contact.id)}>Remove Contact </button> </div>
</div>
)
})
}
</div>
);
}
}
export default App;
&#13;
答案 0 :(得分:1)
问题是你在this
内使用function
,因此this
被函数绑定而不是封闭类。请尝试使用lambda:
this.state.contacts.map((contact, i) => (
<div key={contact.id}>
<br />
<div>First Name:</div>
<span>{contact.first_name}</span>
<div>Last Name:</div>
<span>{contact.last_name}</span>
<div>Email:</div>
<span>{contact.email}</span>
<div>
<button type="button" onClick={() => this.onDismiss(contact.id)}>
Remove Contact
</button>
</div>
</div>
)