[英]Typescript - TypeError this.renderCell is not a function
I am writing a Web app using ReactJS
and Typescript
.我正在使用ReactJS
和Typescript
编写一个 Web 应用程序。
I wrote the following code inside my class我在课堂上写了以下代码
class FractionComponent extends React.Component<any, FractionState>{
constructor(props: any) {
super(props);
this.state = this.createNew();
}
renderBoard() {
const strBoardId = "board";
return (
<Board
id={strBoardId}
itemsRender={this.renderItems}
rowsNumber={this.state.rowsNumber}
columnsNumber={this.state.columnsNumber}
onClick={() => this.handleClick()}
/>
);
} }
renderCell(id: string, coords: FractionCoord) {
return (
<div key={id} className="page_boardCell" />
);
}
renderItems(rows: number, columns: number) {
let rowsArray = [];
let columnsArray: string[] = [];
for (let i = 0; i < rows; i++) {
columnsArray = []
for (let j = 0; j < columns; j++) {
columnsArray.push(`${i}${j}`);
}
rowsArray.push(columnsArray)
}
return (
rowsArray.map((row, ri) => (
<div key={ri} className="page_boardRow">
{columnsArray.map((cellId, index) => this.renderCell(cellId, { "a": ri, "b": index })
)}
</div>
))
);
} }
render() {
return (
<React.Fragment>
{this.renderBoard()}
</React.Fragment>
)
}
} }
function Board(props: BoardProps) {
var classes = ["fractionPage_board"];
if (props.selected) { classes.push("fractionPage_selectedSquare"); }
if (props.isCellError) { classes.push("fractionPage_error"); }
return (
<div key={props.id} className={classes.join(" ")} onClick={props.onClick} style={{ ...props.cellStyle }}>
{props.itemsRender(props.rowsNumber, props.columnsNumber)}
</div>
);
}
interface BoardProps { id: string, onClick: any, itemsRender: any, columnsNumber: number, rowsNumber: number }
But it gives me this error但它给了我这个错误
TypeError: this.renderCell is not a function
When I remove renderCell
function and embedd the code directly in renderItems
it works.当我删除renderCell
函数并将代码直接renderItems
到renderItems
它可以工作。
WHat's the problem could be?可能是什么问题?
Thank you.谢谢你。
EDIT I forget to say that I am passing renderItems
as a props
to another component.编辑我忘了说我将renderItems
作为props
传递给另一个组件。
The callback function passed inside map is an arrow function, in which this
won't refer to the class instance. map 内部传递的回调函数是一个箭头函数,其中this
不会引用类实例。 Change it to a regular function syntax, and things should work fine将其更改为常规函数语法,事情应该可以正常工作
{columnsArray.map(function(cellId, index) { return this.renderCell(cellId, { "a": ri, "b": index })})}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.