首页 > 解决方案 > 无法在静态函数 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

标签: javascriptreactjs

解决方案


不要让它成为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).


推荐阅读