缺少关键位,我不知道它是否在任何地方都有记录,但是您需要使用 JSX 编译器的大写字母 (?) 将其识别为一种类型。
import AllComponents from 'Components';
const FooType = 'Foo';
return (
<div className="wrapper">
<div>Hello World</div>
<AllComponents[FooType] />
</div>
);
编辑 - 根据评论
class Foo extends React.Component {
render() {
return <div>Foo 123</div>;
}
};
class Bar extends React.Component {
render() {
return <div>Bar 123</div>;
}
};
class App extends React.Component {
render() {
const all = {
'Foo': Foo,
'Bar': Bar,
};
// For the sake of the demo, just randomly pick one of the two
// usually this would come from an import, or something similar
const randomKey = ['Foo', 'Bar'][Math.floor(Math.random() * 2)];
// The resolved component must begin with a capital letter
const Type = all[randomKey];
return (
<div>
<Type />
</div>
);
}
};
ReactDOM.render(<App />, document.getElementById('root'));
JSBin:http ://jsbin.com/noluyu/5/edit?js,output
编辑 2
我们典型的动态渲染组件的应用程序,通常在所有组件目录的根目录下都有一个 index.js 文件,它简单地列出了所有可能的组件:
// index.js
export Breadcrumb from './breadcrumb/Breadcrumb';
export Checkbox from './checkbox/Checkbox';
export Comment from './comment/Comment';
然后你所要做的就是:
import AllComponents from './index.js';
const myType = 'Checkbox';
const Type = AllComponents[myType];
.. later ..
return <div><Type /></div>;