我不能在静态函数内调用函数。在包含循环映射以创建列表的静态函数内部,在内部使用a onClick
调用函数,但无法正常工作。我不知道要正确解析功能
ListData.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
答案 0 :(得分:2)
请勿将其设置为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)
。
答案 1 :(得分:0)
静态方法将没有与调用类实例相同的tag
。我建议您将方法设为非静态,我认为没有理由这样做。另一种选择是传递必需的方法(tag
和null
作为附加参数。