1
0

More than 3 years have passed since last update.

Reactでfor文を使う

Last updated at Posted at 2020-11-28

したかったこと

JSX内で表の列をfor文を用いることで、繰り返し処理する。
理由)デザインを変える時に、一つ一つ変更するのが面倒だった。

解決前のコード

<tr>
  <th style={{fontWeight: 'bold',fontSize:40}}>1set</th>
  <th><input style={{height:52, width:80,borderStyle:"none", borderRadius:4}}/><span style={{fontSize:40}}>kg</span></th>
  <th><input style={{height:52, width:70,borderStyle:"none", borderRadius:4}}/><span style={{fontSize:40}}></span></th>
</tr>
<tr>
  <th style={{fontWeight: 'bold',fontSize:40}}>2set</th>
  <th><input style={{height:52, width:80,borderStyle:"none", borderRadius:4}}/><span style={{fontSize:40}}>kg</span></th>
  <th><input style={{height:52, width:70,borderStyle:"none", borderRadius:4}}/><span style={{fontSize:40}}></span></th>
</tr>
<tr>
  <th style={{fontWeight: 'bold',fontSize:40}}>3set</th>
  <th><input style={{height:52, width:80,borderStyle:"none", borderRadius:4}}/><span style={{fontSize:40}}>kg</span></th>
  <th><input style={{height:52, width:70,borderStyle:"none", borderRadius:4}}/><span style={{fontSize:40}}></span></th>
</tr>

解決策

・即時関数を使う。
・for文のループで出力された列を作成したリストにプッシュし、最後にリストを返す。(これをしないでfor文内で値を返すと、1ループ目で値を返してしまいました。)

解決後のコード
{(() =>{
  const item=[];
  for(let i=1; i <5; i++) {
    item.push(
    <tr>
      <th style={{fontWeight: 'bold',fontSize:40}}>{i}set</th>
      <th><input style={{height:52, width:80,borderStyle:"none", borderRadius:4}}/><span style={{fontSize:40}}>kg</span></th>
      <th><input style={{height:52, width:70,borderStyle:"none", borderRadius:4}}/><span style={{fontSize:40}}></span></th>
    </tr>
    )
  }
  return(item)
})()}

結果

スクリーンショット 2020-11-28 17.44.47.png

参考にした記事 - Qiita

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0