2017-09-15 56 views
2

我已經被稱爲「按鈕」的工作組件,該組件使用它:陣營組件與動態標籤名稱不會呈現

import React, { Component } from 'react' 

import Button from './Boxes/Button' 

class AutoGraph extends Component { 

    constructor(props) { 
    super(props) 

    this.placed = { 
     components: [ 
     { 
      type: 'Button', 
      x: 10, 
      y: 10 
     } 
     ] 
    } 

    } 

    render() { 
    return (
     <svg width={this.windowWidth} height={this.windowHeight}> 

     <g id="component-layer">{this.placed.components.map((item, i) => { 
      return React.createElement(item.type, { 
      key: i, 
      x: item.x, 
      y: item.y 
      }) 
     })} 
      <Button x="150" y="20"/> 
     </g> 

     </svg> 
    ) 
    } 
} 

export default AutoGraph 

動態創建的按鈕只呈現爲<按鈕X =「10」 Y =」 10「/ >,但硬編碼的Button組件直接渲染正確後。我如何讓我的動態創建的按鈕使用我的Button組件代碼進行渲染?

回答

2

字符串用於內置類型(diva等)。函數和類表示自定義組件。如果你想使你的自定義組件,你必須是類/函數傳遞:

變化

type: 'Button', 

type: Button, 
+0

謝謝你的工作!我怎樣才能將字符串轉換爲類?我想從字符串'Button'中檢索Button組件,但eval('Button')不起作用。 –

+1

您應該爲要動態加載的組件構建查找表。例如。 'const components = {Button};'(相當於'{Button:Button}'),然後你可以做'React.createElement(components [this.place.type],...)'。 –

1

你必須引用該組件本身,而不是字符串名稱:

{ 
    type: Button, // not a string 
    x: 10, 
    y: 10 
}