警告:道具`className`不匹配〜材质UI css在重新加载时任意中断

时间:2019-05-26 20:49:52

标签: javascript css reactjs material-ui next.js

enter image description here

Video reproducing the error/missing css

知道,该问题在堆栈溢出时已经过时,例如React + Material-UI - Warning: Prop className did not match

但是,当我尝试搜索并研究人们的解决方案时,没有明确的答案。我能找到的所有答案都不符合我的要求。

我的堆栈:

  • Node JS
  • 下一个JS
  • 材料界面

next.js & material-ui - getting them to work之类的问题的答案中我可以得出的结论是,在涉及Next JS和Material UI时,存在某种程度的不兼容。

按代码分类,这是我的Appbar组件。最初,我没有导出我的useStyles对象,但最终却以可怜的尝试将其与Material UI's express guide to "server rendering"一起使用来导出它。必须有一个不涉及像我拥有的​​每个文件一样进行更改的修补程序。

import React from 'react';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import IconButton from '@material-ui/core/IconButton';
import Typography from '@material-ui/core/Typography';
import InputBase from '@material-ui/core/InputBase';
import { fade } from '@material-ui/core/styles/colorManipulator';
import { makeStyles } from '@material-ui/core/styles';
import MenuIcon from '@material-ui/icons/Menu';
import SearchIcon from '@material-ui/icons/Search';
import {connectSearchBox} from 'react-instantsearch-dom';

const useStyles = makeStyles(theme => ({
    root: {
        flexGrow: 1,
    },
    menuButton: {
        marginRight: theme.spacing(2),
    },
    title: {
        flexGrow: 1,
        display: 'none',
        [theme.breakpoints.up('sm')]: {
            display: 'block',
        },
    },
    search: {
        position: 'relative',
        borderRadius: theme.shape.borderRadius,
        backgroundColor: fade(theme.palette.common.white, 0.15),
        '&:hover': {
            backgroundColor: fade(theme.palette.common.white, 0.25),
        },
        marginLeft: 0,
        width: '100%',
        [theme.breakpoints.up('sm')]: {
            marginLeft: theme.spacing(1),
            width: 'auto',
        },
    },
    searchIcon: {
        width: theme.spacing(7),
        height: '100%',
        position: 'absolute',
        pointerEvents: 'none',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
    },
    inputRoot: {
        color: 'inherit',
    },
    inputInput: {
        padding: theme.spacing(1, 1, 1, 7),
        transition: theme.transitions.create('width'),
        width: '100%',
        [theme.breakpoints.up('sm')]: {
            width: 300,
            '&:focus': {
                width: 400,
            },
        },
    }
}));

function SearchBox({currentRefinement, refine}){
    const classes = useStyles();
    return(
        <InputBase
            type="search"
            value={currentRefinement}
            onChange={event => refine(event.currentTarget.value)}
            placeholder="Search by state, park name, keywords..."
            classes = {{
                root: classes.inputRoot,
                input: classes.inputInput,
            }}
        />
    )
}

const CustomSearchBox = connectSearchBox(SearchBox);

function SearchAppBar() {
    const classes = useStyles();
    return (
        <div className={classes.root}>
            <AppBar position="static" color="primary">
                <Toolbar>
                    <IconButton
                        edge="start"
                        className={classes.menuButton}
                        color="inherit"
                        aria-label="Open drawer"
                    >
                        <MenuIcon />
                    </IconButton>
                    <Typography className={classes.title} variant="h6" noWrap>
                        Title
                    </Typography>
                    <div className={classes.search}>
                        <div className={classes.searchIcon}>
                            <SearchIcon />
                        </div>
                        <CustomSearchBox/>
                    </div>
                </Toolbar>
            </AppBar>
        </div>
    );
}

export {SearchAppBar, useStyles};

2 个答案:

答案 0 :(得分:0)

我只是在互联网的随机区域四处寻找该错误的答案,在Github问题上偶然npm installstyled-components作为this answer的一部分(因为它们有一个与Material UI中名为ServerStyleSheet的对象非常相似的对象(与Material UI的ServerStyleSheets相比),因此显然不起作用。

但是...... 我最终只是使用ServerStyleSheet修复程序尝试使其与Material UI的ServerStyleSheets对象一致,并结束了这个新的_document.js

我仍然很傻,我能够重构一个完全不同的修复程序来完成这项工作,但是我对其进行了测试,它完全解决了问题,现在重新加载就可以了。

import Document, { Html, Head, Main, NextScript } from 'next/document';
import {ServerStyleSheets} from "@material-ui/styles";

class MyDocument extends Document {
    static async getInitialProps(ctx) {
        const sheet = new ServerStyleSheets();
        const originalRenderPage = ctx.renderPage;

        try{
            ctx.renderPage = () => originalRenderPage({
                enhanceApp: App => props => sheet.collect(<App {...props}/>)
            });

            const initialProps = await Document.getInitialProps(ctx);
            return { ...initialProps,
                styles: (
                    <>
                        {initialProps.styles}
                        {sheet.getStyleElement()}
                    </>
                )
            }
        } finally {
            ctx.renderPage(sheet)
        }

    }
    render() {
        return (
            <Html>
                <Head>
                    <link rel="shortcut icon" type="image/png" href="../static/favicon.ico"/>
                    <style>{`body { margin: 0 } /* custom! */`}</style>
                    <meta name="viewport"content="width=device-width, initial-scale=1.0" />
                </Head>
                <body className="custom_class">
                    <Main />
                    <NextScript />
                </body>
            </Html>
    )}
}

export default MyDocument;

如果您想了解它的工作原理是多么疯狂,这里是针对styled-components中相同错误的解决方案:

导出默认的MyDocument;

import Document from 'next/document'
import { ServerStyleSheet } from 'styled-components'

export default class MyDocument extends Document {
    static async getInitialProps (ctx) {
        const sheet = new ServerStyleSheet()
        const originalRenderPage = ctx.renderPage

        try {
            ctx.renderPage = () =>
                originalRenderPage({
                    enhanceApp: App => props => sheet.collectStyles(<App {...props} />)
                })

            const initialProps = await Document.getInitialProps(ctx)
            return {
                ...initialProps,
                styles: (
                    <>
                        {initialProps.styles}
                        {sheet.getStyleElement()}
                    </>
                )
            }
        } finally {
            sheet.seal()
        }
    }
}

我希望这可以帮助某人解决Material-UI + Next.js的麻烦

答案 1 :(得分:0)

就我而言,在 makeStyle 钩子中添加 { name: "MuiExample_Component" } 是出于某种原因。我在互联网上挖掘时找到了这个解决方案。如果有人能告诉我这是否是一个好的解决方案,我将不胜感激,但这是代码:

const useStyles = makeStyles({
    card: {
        backgroundColor: "#f7f7f7",
        width: "33%",
    },
    title: {
        color: "#0ab5db",
        fontWeight: "bold",
    },
    description: {
        fontSize: "1em"
    }
}, { name: "MuiExample_Component" });