簡體   English   中英

無法在靜態函數ReactJs中調用函數

[英]Can't call function inside static function ReactJs

我不能在靜態函數內調用函數。 在包含循環映射以創建列表的靜態函數內部,在內部我使用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

static關鍵字為類定義靜態方法。 在類的實例上不會調用靜態方法 而是在類本身上調用它們。 這些通常是實用程序功能,例如用於創建或克隆對象的功能。

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Classes/static


進行更改之后,請不要忘記更改render以使用this.renderForecastsTable(this.state.forecasts)而不是ListData.renderForecastsTable(this.state.forecasts)

靜態方法將不會有相同的this是調用的類實例。 我建議您將方法設為非靜態,我認為沒有理由這樣做。 另一種替代方法是通過所需的方法( this.handleDeletethis.getClientReport為附加參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM