简体   繁体   English

ReactJS 按钮未调用 onClick 事件

[英]ReactJS Button not calling the onClick event

So my problem here is that my button onClick method is not calling my function.所以我的问题是我的按钮 onClick 方法没有调用我的 function。

import React, { Component } from 'react';
import axios from 'axios';



export class FetchData extends  Component {
  static displayName = FetchData.name;

  constructor(props) {
    super(props);
    this.state = { users: [], loading: true };
  }

  componentDidMount() {
    this.getDataAxios();
  }

  deleteItem(){
    console.log("blabla");
    return this.state;
  }

  editItem = () => {
    console.log("asdasd")
  }


  static renderUsersTable(users) {
    return (
      <table className='table table-striped' aria-labelledby="tabelLabel">
        <thead>
          <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Type</th>
            <th>Action</th> 
          </tr>
        </thead>
        <tbody>
        {users.map(items => 
        <tr key=""> 
        <td>{items.id}</td>
        <td>{items.name}</td>
        <td>{items.age}</td> 
        <td>  
            <button type="button" onClick={this.deleteItem} className="btn btn-danger">Delete</button>  
        </td>
        <td>  
            <button type="button" onClick={this.editItem} className="btn btn-success">Edit</button>  
        </td>
         </tr> 

         )} 
        </tbody>
      </table>
    );
  }

  render() {
    let contents = this.state.loading
      ? <p><em>Loading...</em></p>
      : FetchData.renderUsersTable(this.state.users);

    return (
      <div>
        <h1 id="tabelLabel" >API info</h1>
        <p>This component demonstrates fetching data from the api.</p>
        {contents}
      </div>
    );
  }

  async getDataAxios(){
    const response = await axios.get("https://localhost:5001/inventory");
    const data = await response.data;
    this.setState({ users: data, loading: false });
    console.log(data);
  } catch(err) {
      console.log(err)
 }
}

am I maybe doing something wrong with the constructor?我可能对构造函数做错了吗?

Neither of Edit or Delete buttons are even called when clicked, my console does not log anything at all, neither I get return of the state.单击时甚至都不会调用“编辑”或“删除”按钮,我的控制台根本没有记录任何内容,也没有返回 state。

PS Some of the property names aren't 100% correct due to the current DATABASE. PS 由于当前的数据库,一些属性名称不是 100% 正确的。

Found the solution.找到了解决方案。

Change改变

FetchData.renderUsersTable

to

this.renderUsersTable 

and remove static from the renderUsersTable method.并从renderUsersTable方法中删除static And don't forget to add the bind inside the constructor:并且不要忘记在构造函数中添加绑定:

this.deleteItem = this.deleteItem.bind(this);

Change改变

deleteItem = () => {

to:至:

deleteItem() {

and add this bind inside your constructor:并在您的构造函数中添加this绑定:

this.deleteItem = this.deleteItem.bind(this);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM