简体   繁体   English

反应 - map function 内的 Map

[英]React - Map inside a map function

I'm looking to create a simple multiplication table using React.我正在寻找使用 React 创建一个简单的乘法表。 I've got the following code where I'm trying to loop through an array.我有以下代码,我试图循环遍历一个数组。

{array.map((num) => {
  return (
    <tr>
      <th>{num}</th>

      {array.map((x) => {
        return <td>{x}</td>;
      })}
    </tr>
  );
})}

I'm getting the error 'num.map is not a function'我收到错误“num.map 不是函数”

I understand that num is not a function, but I wanted to check if there is a way I could basically create a nested loop?我知道 num 不是 function,但我想检查是否有一种方法可以基本上创建嵌套循环? If not, my alternative would be to convert a string to JSX, but I wanted to check whether there's a way I could achieve this with map first.如果没有,我的替代方法是将字符串转换为 JSX,但我想检查是否有一种方法可以首先使用 map 来实现这一点。

You can use Array.from() to create a range of numbers, iterate them, and produce react nodes:您可以使用Array.from()创建一系列数字,对其进行迭代并生成反应节点:

 const renderRange = (start, end, cb) => Array.from( { length: end - start + 1 }, (_, i) => cb(i + start) ) const Demo = () => ( <table> <tbody> {renderRange(1, 10, x => ( <tr key={x}> {renderRange(1, 10, y => ( <td key={x * y}> {x * y} </td> ))} </tr> ))} </tbody> </table> ) ReactDOM.render( <Demo />, root )
 td { border: 1px solid black; padding: 2px; }
 <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <div id="root"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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