我正在开发一个组件映射函数,该函数循环遍历具有键的对象列表type
。该函数返回一个React组件类型的对象,它看起来像这样:
import _ from 'lodash';
import cellBodyTypes from './cellBodyTypes';
import {
GenericCellBody,
SubData
} from './components/CellBody';
const columnMapper = {};
_.forEach(cellBodyTypes, (type) => {
switch (type) {
case cellBodyTypes.SUB_DATA:
columnMapper[type] = SubData;
break;
case cellBodyTypes.DEFAULT:
columnMapper[type] = GenericCellBody;
break;
default:
columnMapper[type] = GenericCellBody;
}
});
export default columnMapper;
Run Code Online (Sandbox Code Playgroud)
它的用法如下:
renderCellBody = (columnType, cellData, index) => {
const type = columnType || cellBodyTypes.DEFAULT;
const CellBodyComponent = columnMapper[type];
return <CellBodyComponent />;
}
Run Code Online (Sandbox Code Playgroud)
渲染看起来像这样:
render (
<div>
{this.props.cellData.map((cell, index) => ( …
Run Code Online (Sandbox Code Playgroud)