阵营组件与动态标签名称不会呈现
问题描述:
我已经被称为“按钮”的工作组件,该组件使用它:阵营组件与动态标签名称不会呈现
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组件代码进行渲染?
答
字符串用于内置类型(div
,a
等)。函数和类表示自定义组件。如果你想使你的自定义组件,你必须是类/函数传递:
变化
type: 'Button',
到
type: Button,
答
你必须引用该组件本身,而不是字符串名称:
{
type: Button, // not a string
x: 10,
y: 10
}
谢谢你的工作!我怎样才能将字符串转换为类?我想从字符串'Button'中检索Button组件,但eval('Button')不起作用。 –
您应该为要动态加载的组件构建查找表。例如。 'const components = {Button};'(相当于'{Button:Button}'),然后你可以做'React.createElement(components [this.place.type],...)'。 –