javascript - 无法在静态函数 ReactJs 中调用函数
问题描述
我不能在静态函数中调用函数。在包含循环映射的静态函数内部创建一个列表,在循环内部我调用函数使用a onClick
但不工作。我不知道正确解析函数
列表数据.js
constructor(props) {
super(props);
this.state = {
forecasts: [],
loading: true
};
// This binding is necessary to make "this" work in the callback
this.getClientReport = this.getClientReport.bind(this);
this.handleDelete = this.handleDelete.bind(this);
fetch('api/SampleData/Employees')
.then(response => response.json())
.then(data => {
this.setState({ forecasts: data, loading: false });
});
}
//handle download file
getClientReport(id) {
alert('test')
}
//handle delete
handleDelete(id) {
alert('test')
}
//handle table
static renderForecastsTable(forecasts) {
return (
<table className='table table-striped'>
<thead>
<tr>
<th>No</th>
<th>Name</th>
<th>Photo</th>
<th>Height</th>
<th>Weight</th>
<th></th>
</tr>
</thead>
<tbody>
{forecasts.map((forecast, index) =>
<tr key={forecast.employeeId}>
<td>{index + 1}</td>
<td>{forecast.employeeName}</td>
<td><a onClick={() => this.getClientReport(forecast.employeeId)}>Download File</a></td>
<td>{forecast.height}</td>
<td>{forecast.weight}</td>
<td>
<Link to={"/add-list/" + forecast.employeeName}>Edit</Link> |
<a onClick={() => this.handleDelete(forecast.employeeId)}>Delete</a>
</td>
</tr>
)}
</tbody>
</table>
);
}
render() {
let contents = this.state.loading
? <p><em>Loading...</em></p>
: ListData.renderForecastsTable(this.state.forecasts);
return (
<div>
<h2>List Employee</h2>
{contents}
</div>
);
}
handleDelete 和 getClientReport 不在 HTML 中创建 onclick
解决方案
不要让它成为static
关键字定义类的
static
静态方法。不会在类的实例上调用静态方法。相反,它们是在类本身上调用的。这些通常是实用函数,例如创建或克隆对象的函数。
(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static)
进行更改后,不要忘记更改您render
的使用this.renderForecastsTable(this.state.forecasts)
而不是ListData.renderForecastsTable(this.state.forecasts)
.
推荐阅读
- c# - Entity Framework Core 数据库-优先选择特定列
- gremlin - Gremlin - AWS Neptune - 当按顶点上不存在的属性排序时发出问题
- python - 我是否需要包含 Python PDF Toolkit 或 pypdftk 作为 Lambda 层?
- r - 在模型中交互时,使用“caret::train()”构建的线性模型上的“predict.lm()”出错
- php - 按给定的顺序突出显示多个搜索词
- elasticsearch - ElasticSearch 将关键字字段转换为文本+关键字
- javascript - 试图弄清楚如何通过删除本地存储中的所有行来删除表中的行
- next.js - 指定的模块无法找到。\\?\d:\next.js\firstapp\node_modules\@next\swc-win32-x64-msvc\next-swc.win32-x64-msvc.node
- r - 如何摆脱矩阵顶部的 dim1、dim2、...?
- ibm-midrange - RPGLE/free - 动态指定数据区库