繁体   English   中英

如何在 React 中使用 Material-UI 覆盖 react-data-grid 样式

[英]How to override react-data-grid styles with Material-UI in React

假设我有一个主题文件:

主题.js:

import {createMuiTheme} from "@material-ui/core/styles";

export const myTheme = createMuiTheme({
    palette: {
        text: {
            color: "#545F66",
        },
    },
});

和 App.js 文件,其中渲染看起来像这样:

return (
        <MuiThemeProvider theme={myTheme}>
            <CssBaseline />
            <MyComponent />
        </MuiThemeProvider>
    );

现在我知道我可以通过 withStyles 访问主题:

const StyledMyComponent = withStyles(theme => ({
    something: {
        color: theme.palette.text.color
    }    
}))(props => <MyComponent {...props} />);

但我想要实现的是不同的东西。 MyComponent 是一个非常大的组件,例如具有名为“react-table-1”的类,我想要的是将类颜色“react-table-1”设置为 theme.palette.text ,如下所示:

const StyledMyComponent = withStyles(theme => ({
    "react-table-1": {
        color: theme.palette.text
    }    
}))(props => <MyComponent {...props} />);

但显然它不起作用。 有谁知道这是否可能? 我怎样才能做到这一点。

我可以在 css 文件中设置“react-table-1”颜色,但我想通过按钮在 react 内部更改它,这就是为什么我需要这样的东西。

现场演示: https : //stackblitz.com/edit/react-jt9xs1

您可能想为 className 尝试嵌套选择器

我发现你不能简单地将className添加到ReactDataGrid ,它可能与这个库有关,你可以为它做一个解决方法。

一些注意点:

  • 如果你检查 DOM 结构,你会发现ReactDataGrid Root 类是react-grid-Container ,而不是react-grid-Main
  • Material-UI withStyles用作组件的 HOC,具体用法请参考底部链接。
  • 帖子中的问题很少与主题相关,您可以正常使用主题。
  • 如果你想用样式绑定你的按钮,制作一个样式钩子的外层并将状态传递给makeStyles就可以了。
import React, { useState } from "react";
import ReactDataGrid from "react-data-grid";
import { makeStyles } from "@material-ui/core";

const columns = [
  { key: "id", name: "ID" },
  { key: "title", name: "Title" },
  { key: "complete", name: "Complete" }
];

const rows = [
  { id: 0, title: "Task 1", complete: 20 },
  { id: 1, title: "Task 2", complete: 40 },
  { id: 2, title: "Task 3", complete: 60 }
];

const useStyles = makeStyles(theme => ({
  root: {
    "& div.react-grid-Container": {
      color: "red",
      // color: theme.palette.text.color
    }
  }
}));

const App = () => {
  const classes = useStyles();
  const [row, setRow] = useState([]);
  const onBrutForce = e => {};
  return (
    <div className={classes.root}>
      <ReactDataGrid
        columns={columns}
        rowGetter={i => rows[i]}
        rowsCount={3}
        enableCellSelect={true}
      />
      <br />
      This is what i want to achieve but with "ChangeTheme" button. <br />
      Because i want to set the style to other components too. <br />
      <button onClick={onBrutForce} style={{ margin: "10px" }}>
        (click me)
      </button>
    </div>
  );
};

export default App;

编辑陌生工人4pk8w


相关造型QA:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM