gpt4 book ai didi

javascript - 无法在静态函数ReactJs中调用函数

转载 作者:行者123 更新时间:2023-11-29 18:40:51 25 4
gpt4 key购买 nike

我无法在静态函数中调用函数。在包含循环映射以创建列表的静态函数内部,在循环内部我使用 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

最佳答案

不要让它成为static

The static keyword defines a static method for a class. Static methods aren't called on instances of the class. Instead, they're called on the class itself. These are often utility functions, such as functions to create or clone objects.

( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static )


进行更改后,不要忘记更改您的render 以使用this.renderForecastsTable(this.state.forecasts) 而不是ListData.renderForecastsTable( this.state.forecasts).

关于javascript - 无法在静态函数ReactJs中调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57035651/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com