我有几个组件。
formFields / index.js
export {default as description} from './description/description.component'
export {default as title} from './title/title.component'
我导入它们并获取mainComponent
中的FormField列表import * as FormFields from '../formFields'
如何在渲染功能中使用它们?
这是我失败的尝试之一:
import * as FormFields from '../formFields'
render() {
let properties = ['description', 'title'];
let getComponent = (type) => {
let formElement = FormFields[type]
return <formElement/>
}
return (
<div>
{properties.map((property, i) => {
return (
<div key={i}>
{getComponent(property)}
</div>
);
})}
</div>
)
}
这个实验很成功:
render() {
let EditComponent = FormFields['description']
return (
<div>
<EditComponent/>
</div>
)
}
答案 0 :(得分:2)
这是一个简单的例子,它也传递相同的道具。它本质上是一个组件数组,您可以映射,然后简单地渲染。
class Description extends React.Component {
render() {
return <div>{this.props.prop}</div>;
}
}
class Title extends React.Component {
render() {
return <div>{this.props.prop}</div>;
}
}
const myComponents = [
Description,
Title,
];
class App extends React.Component {
render() {
return (
<div>
{myComponents.map((FormField, i) => <FormField key={i} prop="Hello World!" /> )}
</div>
);
}
}
ReactDOM.render(<App/>, document.getElementById('View'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="View"></div>