【问题标题】:Rendering grid in React using lodash使用 lodash 在 React 中渲染网格
【发布时间】:2018-03-07 08:52:42
【问题描述】:

我很难为我的测试项目渲染一个简单的网格。 不想手动创建网格,因为更大的网格不仅会很麻烦,而且代码也会很混乱,所以我想我应该使用 lodash。

但是,我似乎无法渲染网格,即使我在开发工具中检查它也是不可见的。有人能指出我的错误吗?

如有必要,我也可以使用 lodash 以外的其他工具。

代码如下:

import React from 'react';
import _ from 'lodash';
import './game.css';


const GRID = [
    [{x: 1, y:3}, {x:2, y:3}, {x:3,y:3}],
    [{x: 1, y:2}, {x:2, y:2}, {x:3,y:2}],
    [{x: 1, y:1}, {x:2, y:1}, {x:3,y:1}],
]
class Game extends React.Component {
    renderGrid() {
      return _.map(GRID, row =>{
            _.map(row, cell =>{
                return <div style={{height: 100 + 'px', width: 100+ 'px'}}> {cell.x}, {cell.y} </div>
            })
        })
    }

    render() {
        return (
            <div className="game">
                {this.renderGrid()}
            </div>
        )
    }
}

export default Game;

【问题讨论】:

    标签: javascript reactjs lodash


    【解决方案1】:

    你不会返回内部地图结果,一旦你这样做了,它就会起作用

    renderGrid() {
          return _.map(GRID, row =>{
               return  _.map(row, (cell, index) =>{
                    return <div key={index} style={{height: 100 + 'px', width: 100+ 'px'}}> {cell.x}, {cell.y} </div>
                })
            })
        }
    

    Working codesandbox

    【讨论】:

    • 确实你是对的,为了使它成为一个网格,我还必须将每一行包装在网格中并给它一个适当的类。谢谢
    【解决方案2】:

    在您的情况下,数组内置 map 函数应该足够了。
    不要忘记为地图中的每个元素指定一个唯一键

    提示:

    • items.map(item =&gt; item)items.map(item =&gt; { return(item); }) 的简写格式
    • 如果您将数字放入内联 css 样式,则默认使用 'px' 单位。

    根据您的输入:

    class Game extends Component {
      render() {
        return (
          <div className="game">
          {
            GRID.map((row, rowIdx) => (
              row.map((cell, cellIdx) => (
                <div 
                  key={`${rowIdx}-${cellIdx}`}
                  style={{ height: 100, width: 100 }} 
                >
                {cell.x}, {cell.y}
                </div>
              ))
            ))
          }
          </div>
        );
      }
    }

    此代码有codeandbox演示:https://codesandbox.io/s/2px4znwopr

    希望这个答案能有所帮助。

    【讨论】:

    • 它也可以,谢谢,不知道我为什么推lodash
    • 我喜欢导入尽可能少的包,但很可能 lodash 无论如何都会被其他包使用。所以这完全取决于你的喜好。顺便说一句,如果你看一下 lodash 源代码,它基本上是默认 map 方法的包装器。
    【解决方案3】:

    使用引导程序渲染网格的完整解决方案:

     renderGrid() {
            return _.map(GRID, row => {
                return <div className="row"> {_.map(row, cell => {
                    return <div style={{ height: 100 + 'px', width: 100 + 'px' }}> {cell.x}, {cell.y} </div>
                })
                } </div>
            })
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-29
      • 2017-09-14
      • 2020-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多