React 渲染动态内部组件 [英] React Rendering Dynamic Inner Components
本文介绍了React 渲染动态内部组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这个例子说明了我正在尝试做的事情.
目标是拥有一个动态组件数组并将其呈现在屏幕上.我无法进行渲染部分.
从'prop-types'导入PropTypes;从反应"导入反应;从 './MyComponent1.jsx' 导入 MyComponent1从 './MyComponent2.jsx' 导入 MyComponent2导出默认类 KneatModalContent 扩展 React.Component {构造函数(){极好的();this.components = [MyComponent1, MyComponent2];}使成为() {返回 ({this.components.map(function (component, i) {return <{component}key={i}/>})})}}
我也尝试将数组创建为 [<MyComponent1/>, <MyComponent2/>]
,并尝试渲染为 React.createElement(component,{key:i})
但仍然找不到解决方案 =(
解决方案
要创建动态组件,您只需执行以下操作
constructor() {极好的();this.components = [MyComponent1, MyComponent2];}使成为() {返回 ({this.components.map(function (Component, i) {return <组件键= { i }/>})})}
This example illustrates what i`m tryng to do.
The goal is to have a dynamic component array and render it o the screen. I`m not being able to do the rendering part.
import PropTypes from 'prop-types';
import React from 'react';
import MyComponent1 from './MyComponent1.jsx'
import MyComponent2 from './MyComponent2.jsx'
export default class KneatModalContent extends React.Component {
constructor() {
super();
this.components = [MyComponent1, MyComponent2];
}
render() {
return (
<div className='modal-contents'>
{this.components.map(function (component, i) {
return <{ component } key= { i } />
})}
</div>
)
}
}
I have tryed to create the array as [<MyComponent1/>, <MyComponent2/>]
as well, as tryed to render as React.createElement(component, {key:i})
but still couldnt find a solution =(
解决方案
In order to create dynamic component, you could just do the following
constructor() {
super();
this.components = [MyComponent1, MyComponent2];
}
render() {
return (
<div className='modal-contents'>
{this.components.map(function (Component, i) {
return <Component key= { i } />
})}
</div>
)
}
这篇关于React 渲染动态内部组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文