У меня есть карты, созданные с использованием material-UI. Проблема в том, что когда страница загружается или перезагружается, карточки выглядят так, как слева. Кажется, на нем нет никакого css. Через несколько секунд это выглядит так, как должно выглядеть. Это из-за того, что я делаю со своей стороны, или просто так работает Material-UI?
import React, { Component } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardActionArea from '@material-ui/core/CardActionArea';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import CardMedia from '@material-ui/core/CardMedia';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
class ImgMediaCard extends Component {
constructor(props){
super(props)
}
render(){
return (
<div className = "Cards-div">
<Card className = "Cards">
<CardActionArea>
<CardMedia
component = "img"
alt = {this.props.imgAlt}
height = "300"
image = {this.props.imgLink}
title = {this.props.imgTitle}
/>
<CardContent>
<Typography gutterBottom variant = "h5" component = "h2">
{this.props.title}
</Typography>
<Typography variant = "body2" color = "textSecondary" component = "p">
{this.props.text}
{this.props.technologies}
</Typography>
</CardContent>
</CardActionArea>
<CardActions>
<Button size = "small" color = "primary">
Visit
</Button>
</CardActions>
</Card>
</div>
)};
}
export default ImgMediaCard;
Репозиторий Github: https://github.com/Kohdz/порт
обязательно выложу код
Проблема только в картах? Все остальное с Material UI работает нормально?
нет, когда у меня была кнопка, была та же проблема. Я добавляю код на github и собираюсь дать ссылку. Спасибо за интерес,
вот репозиторий github: github.com/Кодз/порт
Это не было проблемой, извините, я исследую это немного больше.






Хорошо, после того, как я немного поборолся с этой штукой, я, наконец, понял. Ключ, кажется, находится в /pages/_document.js. Мне нужно было сделать две вещи: вернуть _document.js и заставить его обрабатывать getInitialProps(), а также добавить flush из styled-jsx.
import React from 'react';
import Document, { Head, Main, NextScript } from 'next/document';
import { ServerStyleSheets } from '@material-ui/styles';
import flush from 'styled-jsx/server';
import { createMuiTheme } from '@material-ui/core/styles';
import red from '@material-ui/core/colors/red';
const theme = createMuiTheme({
palette: {
primary: {
main: '#556cd6',
},
secondary: {
main: '#19857b',
},
error: {
main: red.A400,
},
background: {
default: '#fff',
},
},
});
class MyDocument extends Document {
render() {
return (
<html lang = "en" dir = "ltr">
<Head>
<meta charSet = "utf-8" />
<meta
name = "viewport"
content = "minimum-scale=1, initial-scale=1, width=device-width, shrink-to-fit=no"
/>
<meta name = "theme-color" content = {theme.palette.primary.main} />
<link
rel = "stylesheet"
href = "https://fonts.googleapis.com/css?family=Roboto:300,400,500&display=swap"
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</html>
);
}
}
MyDocument.getInitialProps = async ctx => {
const sheets = new ServerStyleSheets();
const originalRenderPage = ctx.renderPage;
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: App => props => sheets.collect(<App {...props} />),
});
const initialProps = await Document.getInitialProps(ctx);
return {
...initialProps,
styles: (
<React.Fragment>
{sheets.getStyleElement()}
{flush() || null}
</React.Fragment>
),
};
};
export default MyDocument;Пример пользовательского интерфейса материала здесь.тоже была интересная темка
Спасибо за помощь. можете ли вы уточнить, что вы подразумеваете под «вернуть _document.js». Я вставил приведенный выше код в свой /pages/_document.js, но проблема все еще сохраняется.
Вы переименовали _document.js во что-то другое. Судя по тому, что я прочитал, переименование этого файла приводит к тому, что next.js игнорирует файл. _doucment.js. Я думал, что вы сделали это по какой-то причине, потому что вы выполняли getInitialProps в другом месте и больше не нуждались в этом.
Теперь мне любопытно, готовы ли вы поделиться своим проектом, если он у вас есть в репозитории? Выглядит как интересная задача для решения. Это определенно выглядит неправильно.