You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+TypeScript报错TypeError: this.renderCell is not a function如何解决

问题根因

该错误是类方法的this指向丢失导致的:

  • 你将renderItems作为普通类方法定义,直接把this.renderItems作为props传递给Board子组件时,没有绑定其执行上下文。当Board组件内部调用props.itemsRender()时,函数的执行上下文已经脱离了FractionComponent类实例,严格模式下此时函数内部的this为undefined,自然无法找到挂载在类实例上的this.renderCell方法。
  • 你把renderCell逻辑直接嵌入renderItems就能正常运行,是因为此时不需要再访问this上的方法,避开了this指向错误的问题。
修复方案

有三种常用的修复方式,任选其一即可:

  1. 在构造函数中手动绑定this
    在constructor中添加绑定逻辑:
constructor(props: any) {
  super(props);
  this.state = this.createNew();
  // 新增绑定逻辑
  this.renderItems = this.renderItems.bind(this);
}
  1. 将renderItems改为箭头函数类属性,自动绑定类实例上下文:
renderItems = (rows: number, columns: number) => {
  // 原有逻辑保持不变
}
  1. 传递props时用箭头函数包裹调用,保留当前实例的this指向:
    修改renderBoard中传给Board的itemsRender属性:
<Board
  id={strBoardId}
  itemsRender={(rows, columns) => this.renderItems(rows, columns)}
  rowsNumber={this.state.rowsNumber}
  columnsNumber={this.state.columnsNumber}
  onClick={() => this.handleClick()}
/>

内容的提问来源于stack exchange,提问作者Amine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 18:27:00