简体   繁体   中英

Making a matrix of inputs from user defined inputs

I am trying to do the following in React:

  1. User inputs rows and columns
  2. A grid is created in react of blank inputs, displayed as a grid with the correct dimensions.

So far I have the following. Here I am assuming that the rows and columns that the user has input is 3 for both for brevity:

import React from "react";
import "./App.css";

function App() {
  // create a 3x3 matrix with some blank inputs as values values
  const matrix = Array.apply(null, Array(9)).map(function (x, i) {
    return <input></input>;
  });

  return <div className="App">{matrix}</div>;
}

export default App;

Now this just gives me output that looks as follows:

在此处输入图片说明

Could someone please give me some ideas as to how can turn the above into a 3x3 grid? I want it to eventually adjust based on what row and column values that the user provides.

Currently you are creating a basic array of 9 elements. The most logical way to break it into rows and columns would likely be to create 3 arrays containing 3 input elements each, then separating each group of 3 inputs within something like a <div> so they are rendered on separate lines.

One solution is something like

const matrix = Array.apply(null, Array(3))
  .map(function (x, i) {
    const col = Array.apply(null, Array(3))
      .map(function (y, j) {
        return <input></input>
      });

    return <div>{col}</div>;
  });

As you refine the solution, it may be best to extract the row/column counts to their own variables.

That should get you through the basics of the problem. From there, it may be cleaner to render these as cells in a table, etc.

Feel free to take a look at grid layouts which may be in line with what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM