[英]ReactJS Button not calling the onClick event
所以我的問題是我的按鈕 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)
}
}
我可能對構造函數做錯了嗎?
單擊時甚至都不會調用“編輯”或“刪除”按鈕,我的控制台根本沒有記錄任何內容,也沒有返回 state。
PS 由於當前的數據庫,一些屬性名稱不是 100% 正確的。
找到了解決方案。
改變
FetchData.renderUsersTable
至
this.renderUsersTable
並從renderUsersTable
方法中刪除static
。 並且不要忘記在構造函數中添加綁定:
this.deleteItem = this.deleteItem.bind(this);
改變
deleteItem = () => {
至:
deleteItem() {
並在您的構造函數中添加this
綁定:
this.deleteItem = this.deleteItem.bind(this);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.