我想从其字符串名称动态呈现react组件。 这是我所做的,但它不起作用。可以这样做吗?一个例子真的会有所帮助。
string_name是组件的名称。
var MyComponent = React.createElement(window[string_name], {});
return (
<div className="wrapper">
<div>Hello World</div>
<MyComponent/>
</div>
)
答案 0 :(得分:3)
缺少关键位,我不知道它是否记录在任何地方,但是您需要使用大写字母为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>;
答案 1 :(得分:0)
您可以做的一件事是在MyComponent中需要一个子组件并在返回时呈现它。编写自定义函数以在Child中动态呈现组件,然后在MyComponent中需要它。
var React = require('react');
var Names = React.createClass({
render: function(){
// Map the names and loop through
var names = this.props.names.map(function(name, index){
return(
<div>
<li className="list-group-item" key={index}>
{<h4>{name[index]}</h4>}
</li>
</div>
)
});
}
});
/*We then export the Names component*/
module.exports = Names;
以下是Parent组件。
var React = require('react');
var Names = require('./Names');
var MyComponent = React.createClass({
/*This will set the initial state for any state the component handles. usually empty data*/
getInitialState: function(){
return {
names: ["My Component", "Your Component"]
}
},
render: function(){
return(
<div className="row">
<div className="col-md-4">
<Names names={this.state.names} />
</div>
</div>
);
}
});