【问题标题】:How to render dynamic fields on List Component of React-admin如何在 React-admin 的列表组件上呈现动态字段
【发布时间】:2019-12-13 11:02:05
【问题描述】:

我正在尝试在 React-admin 的列表视图中呈现动态生成的字段。只要我们将每个字段都传递给硬编码,Datagrid 就可以正常工作,但我想根据每个字段的类型动态显示字段(TextField、DateField 等)。

为此,我创建了一个名为 <RenderType/> 的组件,它将具有每行字段的对象作为道具并动态返回 React-admin 组件(TextField、DateField),但它不会显示在不同的列中,但它将所有结果放在一列。

import React from 'react';
import { List, Datagrid, TextField, EditButton } from 'react-admin';

export const PostList = (props) => (
    <List {...props}>
        <Datagrid>
             <RenderType>
            //In this component, I pass the object of the fields 
            //and iterate through them and dynamically
            //return fields based on the field type
            //but I get all fields displayed in one column

        </Datagrid>
    </List>
);

【问题讨论】:

    标签: react-admin


    【解决方案1】:

    我最终使用了 MUI 的 Datagrid 组件,而不是在这个实例中使用 react-admin。

    这是他们的文档: https://mui.com/components/data-grid/

    在 npm 中有一个用于 react admin 的 MUI Datagrid 实现: https://github.com/marmelab/ra-datagrid

    基本上是这样用的:

    数据:

    [{"a": 1, "b": 2, "c": 3}, {"a": 4, "b": 5, "c": 6}, {"a": 7, "b": 8, "c": 9}...]
    

    代码:

    import React from 'react';
    import { Datagrid } from "ra-datagrid"
    import {List} from 'react-admin';
    
    const DynamicGridFields = (props) => {
        // Had an odd issue with this triggering and props not being populated yet
        if(props === undefined || props.data === undefined || Object.values(props.data).length == 0)
            return ""; // Blocking if no data
    
        const columns = [];
        const data = Object.values(props.data);
        const columnList = Object.keys(data[0]);
        for(let index in columnList){
            const column = columnList[index];
            columns.push({
                field: column,
                headerName: column,
                width: 180,
                type: column == "id" ? "string" : "number" // Could do some type checking 
            })
        }
        return <Datagrid columns={columns} rows={data}/>;
    };
    
    const MyList = props => {
        return (
            <List {...props}>
                <DynamicGridFields {...props}/>
            </List>
        )
    };
    
    export default MyList;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-21
      • 1970-01-01
      • 2019-07-21
      • 1970-01-01
      • 1970-01-01
      • 2020-05-06
      • 2021-02-16
      • 1970-01-01
      相关资源
      最近更新 更多