React 中的 for 循环

The for Loop inside React

我正在尝试创建一个动态变化的 table。其列数根据月份的天数(28、29、30 或 31)而变化。

我手动创建了table(但列数固定为31):

https://i.stack.imgur.com/pAvPu.png

这是我尝试根据当月的天数 (28,29,30,31) 手动 select 列数的组件,它在浏览器中没有显示:

const Test = () => {
    // Number of days in the current month
    function daysInCurrentMonth() {
        var now = new Date();
        return new Date(now.getFullYear(), now.getMonth()+1, 0).getDate();
    }

    let a = daysInCurrentMonth();
    return (
        <div>
            <table>
                <tbody>
                    <tr>
                        {() => {
                            for(let i=1;i<=a;i++){
                                 <td>{i}</td>
                            }
                        }}
                    </tr>
                </tbody>
            </table>
        </div>
    );
}

export default Test;

如何在这段代码中使用 for 循环?

您的 JSX 中的代码块没有产生任何值。

尝试替换

 {() => {
    for(let i=1;i<=a;i++){
      <td>{i}</td>
    }
 }}

通过类似的方式:

Array(a).keys().map((i) => <td>{i-1}</td>)

可能有比 Array(a).keys() 更聪明的方法来生成您需要的值范围。

最好使用 map()。

确保你的 i 是一个数组:

i.map(elem -=>  {
    return <td>elem</td>
})

您需要从您在 JSX 中编写的函数中 return td's 并像这样调用该函数:

return (
  <div>
    <table>
      <tbody>
        <tr>
          {(() => {
            let td = [];
            for (let i = 1; i <= a; i++) {
              td.push(<td key={i}>{i}</td>);
            }
            return td;
          })()}
        </tr>
      </tbody>
    </table>
  </div>
);

一种更有效的渲染方式是将函数提取到 JSX 之外:

function daysInCurrentMonth() {
   var now = new Date();
   return new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate();
}

let a = daysInCurrentMonth();

const renderTD = () => {
  let td = [];
  for (let i = 1; i <= a; i++) {
    td.push(<td key={i}>{i}</td>);
  }
  return td;
};

return (
  <div>
    <table>
      <tbody>
        <tr>{renderTD()}</tr>
      </tbody>
    </table>
  </div>
);

如果您想删除 renderTD 函数,您可以创建一个长度为 a 的新数组,但我想这不是一个非常有效的方法。

function daysInCurrentMonth() {
  var now = new Date();
  return new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate();
}
let a = daysInCurrentMonth();

return (
  <div>
    <table>
      <tbody>
        <tr>
          {[...Array(a).fill(0)].map((_, i) => (
            <td key={i}>{i + 1}</td>
          ))}
        </tr>
      </tbody>
    </table>
  </div>
);