【发布时间】:2016-04-26 16:32:31
【问题描述】:
我有一个 react components 数组,我正在尝试输出它们:
this.props.data
[
{
key: 1,
element: 'input',
type: 'text',
placeholder: 'Jamie is Sex'
},
{
key: 2,
element: 'input',
type: 'text',
placeholder: 'Jamie is Not Sex'
}
]
input.component.js
import React from 'react';
const input = React.createClass({
render() {
return (
<input type="text" />
);
}
});
export default input;
导入 components.js
动态代码
import components from '../../componets';
render() {
return (
<form action="">
{this.props.data.map((item, index) => <{components[item.element]} key={index} data={item}/> )}
</form>
//{components[item.element]} which would reference 'input' from components.js
);
}
输出
bundle.js:33283 Uncaught Error: Cannot find module "../components/Form/Form.component.js"webpackMissingModule @ bundle.js:33283(anonymous function) @ bundle.js:33283__webpack_require__ @ bundle.js:20(anonymous function) @ bundle.js:32763__webpack_require__ @ bundle.js:20(anonymous function) @ bundle.js:7464__webpack_require__ @ bundle.js:20(anonymous function) @ bundle.js:48__webpack_require__ @ bundle.js:20(anonymous function) @ bundle.js:40(anonymous function) @ bundle.js:43
bundle.js:99 [WDS] Errors while compiling.
【问题讨论】:
-
哈哈,我刚看到我自己的占位符文本,我是在 2 小时前写的,但它仍然让我发笑。哦,我过着多么糟糕的生活:'(
-
我相信在这种情况下你会想要使用 React.createElement(components[item.element],
) 来动态创建组件。 -
事情是,
componenets[item.elemet]引用了我使用const input = React.createClass({创建的反应组件,所以我不是这样吗? -
好吧,您创建的类实际上并没有创建元素。在您尝试执行
<components[item.element]>时的循环中是您实际创建元素的时间。我不认为 JSX 可以呈现这样的动态组件,因此您需要使用 React.createElement(); facebook.github.io/react/docs/glossary.html -
啊是的,好吧,这是有道理的,我会玩这个
标签: javascript reactjs ecmascript-6 babeljs