映射到 div 网格

问题描述 投票:0回答:1

我正在尝试调整以下内容,以便 4x4 网格显示数字 1 到 n。每个 div 单元格都需要一个 onclick 处理程序。

我尝试修改 在 React 中用彩色图块渲染图表

的最后一个响应
function App() {
     
  
  return (
    <div style={{
      background: "",
      height: "400px",
      width: "400px",
      display: "flex",
      flexWrap: "wrap"
    }}>
      {new Array(16).fill(1).map(n =>{  return <div style={{
    height: "96px",
    width: "96px",
    backgroundColor: "transparent",
    border: "solid 2px white"
  }}>{n}</div>})}
    </div>
  );
}

export default App;

如何获取每个单元格上的数字 1...16?我在上面的 div 中尝试了 {n} - 没有帮助。如何在每个div上添加点击事件处理程序并获取其中的数字?

reactjs mapping closures
1个回答
0
投票

基于问题。只需进行一些调整即可获得解决方案。

如果您按如下方式进行更改,您将得到解决方案。在代码中添加了注释以突出显示更改的部分。

function App() {
     
  
  return (
    <div style={{
      background: "",
      height: "400px",
      width: "400px",
      display: "flex",
      flexWrap: "wrap"
    }}>
      // Additional map to convert Array fill to the index values instead
      {new Array(16).fill().map((_, i) => i+1).map(n =>{  return <div style={{
    height: "96px",
    width: "96px",
    backgroundColor: "transparent",
    cursor: "pointer", // Showing mouse correctly for click action
    border: "solid 2px white",
  }} onClick={() => console.log(n)}>{n}</div>})} // Added a simple onClick function
    </div>
  );
}

export default App;

这只是一个粗略的代码,我确信这段代码将成为更大的 React 应用程序的一部分,并且应该使用组件来更好地组织事物。

© www.soinside.com 2019 - 2024. All rights reserved.