【问题标题】:How do you change the primary colour on a resource basis in react-admin?如何在 react-admin 中根据资源更改原色?
【发布时间】:2021-07-09 19:52:48
【问题描述】:

我有各种资源组件位于 react-admin 管理组件中。管理组件具有自定义布局。但是,每个资源屏幕都有不同的原色,以表示您所在的部分和内容类型。如何将原色的特定主题对象变量传递给每个资源,然后在我的自定义布局中使用?

  <Admin
authProvider={AuthProvider}
dashboard={Dashboard}
dataProvider={graphQLProvider}
history={history}
layout={Layout}
title="Home"
  <Resource name="User" options={{label: 'Administrators'}} list={UserList} show={UserShow} edit={UserEdit}
            create={UserCreate} icon={UserIcon}/>

我应该使用“每个 react-admin 组件”上可用的 className 属性还是有更好的方法?

【问题讨论】:

    标签: material-ui react-admin


    【解决方案1】:

    React-admin 不支持此功能,但您可以使用自定义布局(请参阅Replacing the appbar)和历史位置上的侦听器从 URL 获取资源来实现它。比如:

    import React, { useEffect, useState } from 'react';
    import { useHistory } from 'react-router-dom';
    import { AppBar } from 'react-admin';
    import { makeStyles } from '@material-ui/core/styles';
    
    const useStyles = makeStyles({
       posts: {
           backgroundColor: 'red',
       },
       comments: {
           backgroundColor: 'blue',
       }
    });
    
    const MyAppBar = ({ children }) => {
       const [resource, setResource] = useState();
       const history = useHistory();
       const classes = useStyles();
       useEffect(() => {
          const newResource = extractResourceFromPathname(history.location.pathname); // left as an exercise to the reader
          if (newResource !== resource) {
              setResource(newResource);
          }
       }, [history.location.pathname]);
    
       return <AppBar className={classes[resource]} {...props} />
    }
    

    【讨论】:

    • 虽然,随着我的进步并尝试将原色添加到布局的各个部分,它变得越来越成问题。我如何将主题中的颜色直接传递给 makeStyles 方法,以便我可以将颜色洒在任何地方?
    • makeStyles 接受一个函数作为参数,它接收主题。这样您就可以根据主题设置样式。检查例如这个组件来自material-ui源代码:github.com/mui-org/material-ui/blob/…
    • 谢谢 - 我做了类似的事情。我修改了上面的答案,使其具有一个潜在主题数组,其中 resourceName 作为每个元素的名称,然后在布局页面中,我将历史路径名与主题数组元素匹配。这样我根本不需要修改 makeStyles 类,因为我有正确的个人资源主题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多