簡體   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