2017-02-27 119 views
0

我使用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; 
+1

您只是缺少返回語句 – aw04

回答

1

您的renderSquares缺少退貨。

return this.state.myArray.map

0

當你調用this.renderSquares()渲染功能裏面,這將不是指renderSquares內的主板組件()函數的關鍵字。解決方法之一就是使用綁定:

{this.renderSquares.bind(this)} 

我更喜歡另一種方式 - 使用箭頭功能:

而不是使用renderSquares(),使用定義它:

renderSquares =() => { ... } 

這樣,關鍵字這個將被正確引用到電路板組件。請注意,如果您沒有安裝正確的babel預設(我總是確保使用以下babel預設:react, es2015, and stage-1),則此方法可能不起作用