gpt4 book ai didi

javascript - 通过字符串名称动态实例化子组件 - ReactJs

转载 作者:行者123 更新时间:2023-11-29 21:20:49 25 4
gpt4 key购买 nike

我有一个包含 React Component 字符串名称的数组(“SampleWidget1”);它由外部机制填充。在我的 DashboardInterface 组件中,我想使用该数组,呈现其中包含的组件,并将其显示在 DashboardInterface.render 函数中的其他静态定义的 HTML 中。我如何在 React 中执行此操作?

下面是我的尝试;没有错误,但是渲染的组件从未真正成功地插入到 DOM 中。如果我手动将 SampleWidget1 添加到 DashboardInterface.render 函数 () 中,它会按预期显示。如果我对动态呈现的组件执行相同的操作,它就不会出现。

有什么建议吗?

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>
);
}

});

这是我要渲染的示例组件:

/**
* 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 ) 简短示例

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 ) 完整示例webpackbin 演示


3 ) 多组件示例

 renderWidgets(selected){
return selected.map(e=>{
let Widget =widgets[this.props.widgetsToRender[e-1]];
return <Widget key={e}/>
})
}

webpackbin DEMO

enter image description here

关于javascript - 通过字符串名称动态实例化子组件 - ReactJs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38622714/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com