反应中绑定事件处理程序的麻烦

时间:2017-03-02 21:30:50

标签: reactjs react-dom

  1. 我做错了什么,特别是当我点击它给我的按钮时:未捕获的TypeError:无法读取属性' onDismiss'未定义的

  2. 何时需要将事件处理程序绑定到构造函数?

  3. 
    
    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;
    &#13;
    &#13;

1 个答案:

答案 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>
)