简体   繁体   English

在ReactJS中动态添加子元素

[英]Adding Child Elements Dynamically in ReactJS

I have a Container Element and I would like to allow users to select a list of Widgets (Each Widget is different) that a User can choose to add to the container. 我有一个容器元素,我希望允许用户选择一个小部件列表(每个小部件都不同),用户可以选择添加到容器中。

I have the following code for WidgetContainer: 我为WidgetContainer使用以下代码:

export default class WidgetContainer extends React.Component {

  constructor(props){
    super(props);
    console.log('WidgetContainer() : props=['+props+']');
  }

  render() {
    var widgetsTmp  = '';
    if(this.props.data && this.props.data.widgets){
      widgetsTmp = this.props.data.widgets.map(function(widget){
              return (
                  <WidgetItem data={widget} key={widget.id}/>
              );
          });
    }
    return (
      <div className='container'>
        {widgetsTmp}
      </div>
    );
  }
}

And I am setting the props for WidgetContainer as below in an element which contains WidgetContainer 我在一个包含WidgetContainer的元素中为WidgetContainer设置了道具

<WidgetContainer data={section}/>

And from my Store I am sending the details of the Widgets using the following JSON Object as initial props. 从我的商店中,我将使用以下JSON对象作为初始道具来发送小部件的详细信息。

widgets:
[
  {
    title:'Widget1',
    id:'1'
  },
  {
  title:'Widget2',
  id:'2'
  }
]

I am not sure how I can specify the Widget it self declaratively? 我不确定如何以声明方式自行指定Widget?

The other option is using the children's property of the parent and add them using non JSX Syntax. 另一个选择是使用父级的子级属性,并使用非JSX语法添加它们。

If you can get access to the component class, you can assign it to any capitalized variable name and render it normally via JSX. 如果可以访问组件类,则可以将其分配给任何大写的变量名称,并通常通过JSX进行呈现。

var CapitalizedVariableName = lookupComponentClass(maybeBySomeString);
return <CapitalizedVariableName props={stuff} />;

So, as a basic example: 因此,作为一个基本示例:

import Widget1 from "./widget1";
import Widget2 from "./widget2";

var widgets = {
    'Widget1': Widget1,
    'Widget2': Widget2
};

// ...

if(this.props.data && this.props.data.widgets){
    widgetsTmp = this.props.data.widgets.map(function(widget){
        var WidgetType = widgets[widget.type];
        return (
            <WidgetType data={widget} key={widget.id}/>
        );
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM