在反应中绑定事件处理程序的问题
Trouble with binding event handlers in react
我做错了什么,特别是当我点击它给我的按钮时:Uncaught TypeError: Cannot read 属性 'onDismiss' of undefined
什么时候需要将事件处理器绑定到构造函数?
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;
问题是您在 function
中使用 this
,因此 this
受函数约束,而不是封闭的 class。尝试使用 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>
)
我做错了什么,特别是当我点击它给我的按钮时:Uncaught TypeError: Cannot read 属性 'onDismiss' of undefined
什么时候需要将事件处理器绑定到构造函数?
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;
问题是您在 function
中使用 this
,因此 this
受函数约束,而不是封闭的 class。尝试使用 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>
)