小编Aus*_*ght的帖子

使用额外的 props 将 React 组件分配给变量

我正在开发一个组件映射函数,该函数循环遍历具有键的对象列表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)

javascript reactjs

2
推荐指数
1
解决办法
2万
查看次数

标签 统计

javascript ×1

reactjs ×1