在React.js中使用渲染函数外部的循环
问题描述:
我使用React.js构建了一个跳棋游戏,并且我想要创建一个循环来呈现我的“Square”组件64次,以创建我的“Board”组件。在渲染函数中运行.map函数时,我能够正确渲染Square组件。但是,我不喜欢在render函数中发生.map函数,并且想要调用一个单独的函数,它在render函数中执行相同的操作。当我将.map函数移动到renderSquares函数中时,方块不会被渲染。有人能解释我在这里错过了什么吗?谢谢。在React.js中使用渲染函数外部的循环
import React, { Component } from "react";
import Square from "./Square";
class Board extends Component{
constructor(){
super()
this.state = {
myArray: Array(64).fill(null),
checked: false
}
console.log(this.state.checked)
}
renderSquares(){
this.state.myArray.map(function(obj, key){
return <Square key={key} checked={this.state.checked} />
}, this)
}
render(){
return(
<div className="wrapper">
{this.renderSquares()}
</div>
)
}
}
export default Board;
答
您的renderSquares
缺少退货。
return this.state.myArray.map
等
答
当你调用this.renderSquares()
渲染功能里面,这将不是指renderSquares内的主板组件()函数的关键字。解决方法之一就是使用绑定:
{this.renderSquares.bind(this)}
我更喜欢另一种方式 - 使用箭头功能:
而不是使用renderSquares(),使用定义它:
renderSquares =() => { ... }
这样,关键字这个将被正确引用到电路板组件。请注意,如果您没有安装正确的babel预设(我总是确保使用以下babel预设:react, es2015, and stage-1
),则此方法可能不起作用
您只是缺少返回语句 – aw04