【问题标题】:How to share an instance between 2 List components in a react-admin Resource如何在 react-admin 资源中的 2 个列表组件之间共享实例
【发布时间】:2020-07-17 22:58:20
【问题描述】:

这就是在 react-admin 中实例化组件的方式,但现在我需要在 PostList 和 UserList 之间共享通知实例。我想避免单身。是否可以以某种方式将“通知”对象传递给列表?

import React from 'react';
import PostIcon from '@material-ui/icons/Book';
import UserIcon from '@material-ui/icons/People';
import { Admin, Resource } from 'react-admin';
import jsonServerProvider from 'ra-data-json-server';

import { PostList } from './posts';
import { UserList } from './users';
import { Notifications } from './notifications';

var notifications = new Notifications();

const App = () => (
    <Admin dataProvider={jsonServerProvider('https://jsonplaceholder.typicode.com')}>
        <Resource name="posts" list={PostList} icon={PostIcon} />
        <Resource name="users" list={UserList} icon={UserIcon} />
    </Admin>
);

提前致谢。

【问题讨论】:

  • 为此制作了上下文

标签: reactjs react-admin


【解决方案1】:

在我看来,一切都很好地实现了: https://marmelab.com/react-admin/Theming.html#notifications

import { Layout } from 'react-admin';
import MyNotification from './MyNotification';

const MyLayout = (props) => <Layout {...props} notification={MyNotification} />;

const App = () => (
    <Admin layout={MyLayout} dataProvider={simpleRestProvider('http://path.to.my.api')}>
        // ...
    </Admin>
);

【讨论】:

    【解决方案2】:

    将自定义 props 传递给 &lt;Resource&gt; 组件对我来说不是很有效,所以尝试了几种不同的方法,这是适合我要求的一种。

    因此,您可以将一个默认道具传递给名为options&lt;Resource&gt; 组件,该组件接受一个对象。通常,当您想将label 拉入资源时,您会看到正在使用此道具。这个想法是自定义这个对象 -

    // In App.js
    <Admin dataProvider={jsonServerProvider('https://jsonplaceholder.typicode.com')}>
        <Resource name="posts" list={PostList} icon={PostIcon} options={{ "label": "Posts", "notifications": notifications }} />
        <Resource name="users" list={UserList} icon={UserIcon} options={{ "label": "Users", "notifications": notifications }} />
    </Admin>
    

    然后在您的资源中访问它,例如 -

    // In Posts.js
    export const PostList = (props) => {
        const { notifications, label } = props.options;
        // You have your notifications object here now
        return (
            <List
                {...props}
                title={label}
                bulkActionButtons={false}
                exporter={false}>
                <Datagrid>
                    <DateField showTime={true} sortable={true} source="created_on" label="Timestamp" />
                </Datagrid>
            </List>
        );
    };
    

    如果这对你有用,请告诉我!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多