2
1

More than 5 years have passed since last update.

reactの動的レンダリング

Posted at

前提

サーバーから受け取ったデータでループを回して、renderするコンポーネントを分けたかった。

const itemNode = this.state.items.map(item => {
      return(
        <"item.typeに応じたコンポーネント"/>
      )
    })

item.typeに格納された文字列に対応する、コンポーネントをrenderしたい。
例えば、item.type = 'TextItem' → <TextItem />

試したこと

evalcreateElementを使ってみる。


return(
      React.createElement(eval(item.type), props)
    )

eval(item.type)がundefineになりうまくコンポーネントを呼び出せない。

import ◯◯ from ..
...
console.log(eval(item.type)) // undefineのエラー
console.log(◯◯) // 関数が返ってくる

わかったこと

コンポーネントは変数ではなく関数?でもクラス?とにかく、import ◯◯ from ..でインポートしたら、evalとかを使わず◯◯を直接呼ばないとエラーが出る。

解決策

hashにimportしたコンポーネントを格納しておけば動的に呼び出せる!!

const Components = {
  ButtonItem  : LpButtonItem,
  TextItem    : TextItem,
  ListItem    : ListItem,
  TableItem   : TableItem,
  PictureItem : PictureItem,
}
...

const itemNode = this.state.items.map(item => {
  const Component = Components[item.type]
      return(
        <Component {...this.props}/>
      )
    })

// <Components[item.type] {...this.props}/> はコンパイルしてくれない

最後に

まだ理解しきれてないところがあるので、間違っているところやこうしたらもっと簡単!、などあればコメントお願いします!

2
1
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
2
1