我正在学习React;我有这样的问题。当我调用函数“handleSearch”时,它崩溃了 TypeError:无法读取console.log(this.CONTACTS);
我在构造中定义了CONTACTS。并在输入的onChange中调用方法handleSearch()。然后发生错误。 但是这一切都没问题.CONTACTS.map()
import React, { Component } from 'react';
import Contact from './Contact';
import './Contacts.css';
class ContactList extends Component {
constructor() {
super();
this.CONTACTS = [
{
id: 1,
name: 'Alex',
phone: '777',
image: 'https://78.media.tumblr.com/2b5293dc3133abeab79aa74e151e74f9/tumblr_pa1h148ulz1rzp45wo1_75sq.jpg'
},
{
id: 2,
name: 'Ann',
phone: '888',
image: 'https://78.media.tumblr.com/2b5293dc3133abeab79aa74e151e74f9/tumblr_pa1h148ulz1rzp45wo1_75sq.jpg'
},
{
id: 3,
name: 'Zel',
phone: '999',
image: 'https://78.media.tumblr.com/2b5293dc3133abeab79aa74e151e74f9/tumblr_pa1h148ulz1rzp45wo1_75sq.jpg'
}
];
this.state = {
displayedContacts: this.CONTACTS
};
}
handleSearch(event) {
var query = event.target.value.toLowerCase();
console.log(this.CONTACTS);
}
render() {
return (
<div className="contacts">
<input type="text" className="search-field" onChange={ this.handleSearch }/>
<ul className="contacts-list">
{
this.CONTACTS.map(function(el) {
return <Contact
key={el.id}
name={el.name}
phone={el.phone}
image={el.image} />
})
}
</ul>
</div>
);
}
}
export default ContactList;
答案 0 :(得分:2)
您必须在构造函数中使用bind
。在您的事件处理程序this
中引用DOM节点。请将此行添加到构造函数中:
this.handleSearch = this.handleSearch.bind(this)