我在我的网站上有很多数据表,在大多数情况下,它们的样式相同。我需要将几种不同的样式应用于其中一些样式。我想创建一个全局主题来处理整个网站上的所有事情,包括基本的数据表样式,并且我还想拥有一个本地主题来对各个数据表进行一些调整。 这就是我所拥有的。
https://codesandbox.io/embed/jolly-antonelli-fg1y1
这是这样的结构
<Test>
<PrimaryThemeHere> //All have Border 1px red
<TestChild>
<SecondaryThemeHere> //blue background
<Datatable />
</SecondaryThemeHere>
</TestChild>
<TestChild2>
<SecondaryThemeHere> //Red background
<Datatable />
</SecondaryThemeHere>
<TestChild2>
</PrimaryThemeHere>
</Test>
主要主题如下:
const theme = createMuiTheme({
overrides: {
MuiTableBody: {
root: {
border: "1px solid red"
}
},
MuiTableCell: {
root: {
border: "1px solid red"
}
}
}
});
,嵌套主题如下所示:
getMuiTheme = () =>
createMuiTheme({
overrides: {
MuiTableRow: {
root: {
backgroundColor: "blue"
}
}
}
});
我永远无法使边框红色和背景颜色一起显示。它总是选择一个。如何获得初始主要主题(红色边框1px)与背景颜色或蓝色和红色的组合。
请帮助
答案 0 :(得分:1)
这是文档的相关部分:
可以在以下位置找到处理主题嵌套的代码:
这是当前代码:
// To support composition of theme.
function mergeOuterLocalTheme(outerTheme, localTheme) {
if (typeof localTheme === 'function') {
const mergedTheme = localTheme(outerTheme);
warning(
mergedTheme,
[
'Material-UI: you should return an object from your theme function, i.e.',
'<ThemeProvider theme={() => ({})} />',
].join('\n'),
);
return mergedTheme;
}
return { ...outerTheme, ...localTheme };
}
请注意,最后一行(return { ...outerTheme, ...localTheme };
)正在将两个主题进行浅层合并。由于您的两个主题都指定了overrides
属性,因此localTheme替代将完全替代externalTheme替代。
但是,您可以通过为ThemeProvider提供功能来对两个主题进行更复杂的合并。例如TestChild
可能看起来像这样:
import React, { Component } from "react";
import { MuiThemeProvider } from "@material-ui/core/styles";
import MUIDataTable from "mui-datatables";
const localTheme = {
overrides: {
MuiTableRow: {
root: {
backgroundColor: "blue"
}
}
}
};
const themeMerge = outerTheme => {
// Shallow copy of outerTheme
const newTheme = { ...outerTheme };
if (!newTheme.overrides) {
newTheme.overrides = localTheme.overrides;
} else {
// Merge the overrides. If you have the same overrides key
// in both (e.g. MuiTableRow), then this would need to be
// more sophisticated and you would probably want to use
// a deepMerge function from some other package to handle this step.
newTheme.overrides = { ...newTheme.overrides, ...localTheme.overrides };
}
return newTheme;
};
class TestChild extends Component {
render() {
const columns = [
{
name: "Message"
},
{
name: "Date"
},
{
name: "Dismiss"
}
];
const data = [["test", "15/01/19", "", ""], ["test", "15/01/19", "", ""]];
let options = {
filterType: "dropdown",
responsive: "stacked",
print: false,
search: false,
download: false,
selectableRows: "none"
};
return (
<div>
<MuiThemeProvider theme={themeMerge}>
<MUIDataTable
title={"Test"}
data={data}
columns={columns}
options={options}
/>
</MuiThemeProvider>
</div>
);
}
}
export default TestChild;
在您的沙盒版本中,我仅修复了TestChild2.js。