问题
I have an array that contains React Component string names ("SampleWidget1"); it's populated by an external mechanism. Within my DashboardInterface component, I'd like to consume that array, render the Components contained within it, and display it amongst other statically defined HTML in the DashboardInterface.render function. How can I do this in React?
Below is my attempt; there are no errors, but the rendered components are never actually successfully inserted into the DOM. If I manually add the SampleWidget1 into the DashboardInterface.render function () it displays as expected. If I do the same with the dynamically rendered component, it does not appear.
Any suggestions?
var widgetsToRender = ["SampleWidget1"];
/**
* Dashboard that uses Gridster.js to display widget components
*/
var DashboardInterface = React.createClass({
/**
* Loads components within array by their name
*/
renderArticles: function(widgets) {
if (widgets.length > 0) {
var compiledWidgets = [];
// Iterate the array of widgets, render them, and return compiled array
for(var i=0; i<widgets.length; i++){
compiledWidgets.push(React.createElement(widgets[i] , {key: i}));
}
return compiledWidgets;
}
else return [];
},
/**
* Load the jQuery Gridster library
*/
componentDidMount: function(){
// Initialize jQuery Gridster library
$(".gridsterDashboard ul").gridster({
widget_margins: [10, 10],
widget_base_dimensions: [140, 140],
//shift_larger_widgets_down: false
});
},
render: function() {
// Get the widgets to be loaded into the dashboard
var widgets = this.renderArticles(widgetsToRender);
return (
<div className="gridsterDashboard">
<ul >
{this.widgets}
<SampleWidget1 />
</ul>
</div>
);
}
});
Here is a sample component that I'm trying to render:
/**
* Sample component that return list item that is to be insert into Gridster.js
*/
var SampleWidget1 = React.createClass({
render: function() {
// Data will be pulled here and added inside the list item...
return (
<li data-row="1" data-col="1" data-sizex="2" data-sizey="1">testing fake component</li>
)
}
});
ReactDOM.render(
<DashboardInterface />,
document.getElementById('dashboard')
);
回答1:
for that you should import components and select desired, by key property
1 ) short example
import * as widgets from './widgets.js';
const widgetsToRender = ["Comp1","Comp2","Comp3"];
class App extends Component {
render(){
const Widget = widgets[this.props.widgetsToRender[0]]
return <Widget />
}
}
2 ) Full example
webpackbin DEMO
3 ) Example with multiple components
renderWidgets(selected){
return selected.map(e=>{
let Widget =widgets[this.props.widgetsToRender[e-1]];
return <Widget key={e}/>
})
}
webpackbin DEMO
来源:https://stackoverflow.com/questions/38622714/dynamic-instantiation-of-child-components-by-string-name-reactjs