gpt4 book ai didi

javascript - 从单独的文件导入动态 MaterialUI 主题对象?

转载 作者:行者123 更新时间:2023-12-01 17:16:28 32 4
gpt4 key购买 nike

谁能帮我理解允许从单独文件导入动态主题对象的正确语法?

我正在尝试从媒体查询中获取系统主题,然后动态设置主题。

如果我像这样将所有内容都保留在 App 主函数中,则效果很好: https://stackblitz.com/edit/theme-builder-working-all-in-one?file=index.js

但我想在下面的例子中将它分解成不同的文件进行组织,但我的尝试失败了,我收到错误:themeProvider_js_1.default is not a function

损坏的例子: https://stackblitz.com/edit/theme-builder-broken?file=index.js

这是第二次重构尝试,没有错误,我可以在控制台日志中看到 ThemeObject 存在,但系统主题没有被应用: https://stackblitz.com/edit/theme-builder-broken-btyufg?file=index.js

future 的代码:工作代码,但我想重构它,以便主题和媒体查询对象位于 App 组件之外:

import React from 'react';
import { render } from 'react-dom';
import useMediaQuery from '@material-ui/core/useMediaQuery';
import { createMuiTheme, ThemeProvider } from '@material-ui/core/styles';
import CssBaseline from '@material-ui/core/CssBaseline';

function App() {

const prefersDarkMode = useMediaQuery('(prefers-color-scheme)');

const theme = React.useMemo(
() =>
createMuiTheme({
palette: {
type: prefersDarkMode ? 'dark' : 'light',
},
}),
[prefersDarkMode],
);

return (
<ThemeProvider theme={theme}>
<CssBaseline/>
<p>
Start editing to see some magic happen :)
</p>
</ThemeProvider>
);
}

render(<App />, document.getElementById('root'));

失败的重构尝试:

应用组件

import React from 'react';
import { render } from 'react-dom';
import useMediaQuery from '@material-ui/core/useMediaQuery';
import { createMuiTheme, ThemeProvider } from '@material-ui/core/styles';

import themeBuilder from './themeProvider.js'

function App() {

return (
<ThemeProvider theme={themeBuilder()}>
<p>
Start editing to see some magic happen :)
</p>
</ThemeProvider>
);
}

render(<App />, document.getElementById('root'));

主题构建器

import React from 'react';
import { createMuiTheme } from '@material-ui/core/styles';
import useMediaQuery from '@material-ui/core/useMediaQuery';

function themeBuilder() {

const prefersDarkMode = useMediaQuery('(prefers-color-scheme)');

const theme = React.useMemo(
() =>
createMuiTheme({
palette: {
type: prefersDarkMode ? 'dark' : 'light',
},
}),
[prefersDarkMode],
);

return theme
}

最佳答案

我认为您在 themeProvider.js 中缺少 export default

export default function themeBuilder() {

const prefersDarkMode = useMediaQuery('(prefers-color-scheme)');

const theme = React.useMemo(
() =>
createMuiTheme({
palette: {
type: prefersDarkMode ? 'dark' : 'light',
},
}),
[prefersDarkMode],
);

return theme
}

关于javascript - 从单独的文件导入动态 MaterialUI 主题对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62490582/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com