【问题标题】:styled function doesn't apply styling to componentsstyled 函数不会将样式应用于组件
【发布时间】:2021-06-17 06:46:42
【问题描述】:

这是我第一次与styled-componentsmaterial-ui 合作。

我被要求将 Hook-Api 方法重构为 Styled Components API,因为代码库的其他部分已经使用了它。

我有两个独立的分支,一个使用我原来的方法,一个使用styled 函数。

styled 函数方法不起作用(未应用样式)。我不确定我错过了什么(没有错误,并且在默认的 Material UI 主题之后,我的所有自定义样式似乎都加载到了它们自己的样式标签中)。这是我的一些代码:

import React, { useState, useEffect, SyntheticEvent } from 'react'
import { NextPage } from 'next'
import {
  Avatar,
  Button,
  CssBaseline,
  TextField,
  Link,
  Paper,
  Box,
  Grid,
  Typography,
  styled,
} from '@material-ui/core'

import LockOutlinedIcon from '@material-ui/icons/LockOutlined'
import ErrorOutlineIcon from '@material-ui/icons/ErrorOutline'
import withLayout from 'withLayout'
import { UserContext } from 'context/userContext'
import { useRouter } from 'next/router'
// note: a palette object is defined, there aren't any errors related
// to the palette object references
const ContainerStyled = styled(Grid)({
  height: '100vh',
  color: palette.secondary.dark,
})

const AvatarStyled = styled(Avatar)({
  margin: '8px',
  backgroundColor: palette.secondary.main,
})
const BackgroundImageStyled = styled(Grid)({
  backgroundImage: 'url("/logo_horizontal_white.svg")',
  backgroundRepeat: 'no-repeat',
  backgroundColor: palette.primary.main,
  backgroundSize: '80%',
  backgroundPosition: 'center',
})

const TypographyStyled = styled(Typography)({
  color: palette.secondary.dark,
})

const TextFieldStyled = styled(TextField)({
  '& .MuiOutlinedInput-root.Mui-focused .MuiOutlinedInput-notchedOutline': {
    borderColor: palette.primary.dark,
  },
  '& .MuiInputLabel-outlined.Mui-focused': {
    color: palette.secondary.dark,
  },
})

const LinkStyled = styled(Link)({
  // color: palette.secondary.dark,
  color: 'green',
})

const Login: NextPage = () => {
  // note: some code was removed here, none of it was related
  // to the styling

  const classes = {
    form: {
      width: '100%',
      // marginTop: theme.spacing(1),
      marginTop: '8px',
    },
    paper: {
      // margin: (8, 4),
      margin: '64px 32px',
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
    },
  }

  return (
    <ContainerStyled container="true" component="main">
      <CssBaseline />
      <BackgroundImageStyled item xs={false} sm={4} md={7} />
      <Grid item xs={12} sm={8} md={5} component={Paper} elevation={6} square>
        <div className={classes.paper}>
          <AvatarStyled>
            <LockOutlinedIcon />
          </AvatarStyled>
          <TypographyStyled variant="h5">Sign in</TypographyStyled>
          {loginState.error && (
            <LoginErrorMessage code={loginState.error.response?.status} />
          )}
          <form className={classes.form} onSubmit={loginHandler} noValidate>
            <TextFieldStyled
              variant="outlined"
              margin="normal"
              required
              fullWidth
              id="login-email-input"
              label="Email Address"
              name="email"
              autoComplete="email"
              autoFocus
              onChange={(e) => setEmail(e.target.value)}
            />
            <TextFieldStyled
              variant="outlined"
              margin="normal"
              required
              fullWidth
              name="password"
              label="Password"
              type="password"
              id="password"
              autoComplete="current-password"
              onChange={(e) => setPassword(e.target.value)}
            />
            <Button
              type="submit"
              fullWidth
              variant="contained"
              className={classes.submit}
              disabled={loginState.loading}
            >
              Sign In
            </Button>
            <Grid container>
              <Grid item>
                <LinkStyled
                  href="#"
                  variant="body2"
                >
                  {"Don't have an account? Request it"}
                </LinkStyled>
              </Grid>
            </Grid>
            <Box mt={5}>
              <Copyright />
            </Box>
          </form>
        </div>
      </Grid>
    </ContainerStyled>

有人知道为什么 Styled 组件没有收到他们定义的样式吗?

【问题讨论】:

    标签: reactjs material-ui styled-components


    【解决方案1】:

    如果您查看此example,您可以将另一个函数而不是对象传递给返回的样式函数,该函数接受具有主题属性的对象。

    例如,您的TypographyStyled 看起来像这样:

    const TypographyStyled = styled(Typography)(({ theme: { palette } }) => ({
      color: palette.secondary.dark,
    }))
    

    【讨论】:

      【解决方案2】:

      我不知道如何在这里提供帮助。但是注意到您使用的是 Next.js 对吗?所以一件事是确保你添加了正确的设置,就像这个例子material-ui with next.js

      另外你为什么不试试makeStylescreateStyles 像这样

      const useStyles = makeStyles((theme: Theme) =>
        createStyles({
      containerStyled:{
       height: '100vh',
        color: theme.palette.secondary.dark,
      }
        })
      );
      const ContainerStyled=({children}:{children:JSX.Element}):JSX.Element=>{
       return   <Grid classeName={classes.containerStyled} >
            {children}
           </Grid>
      }
      

      【讨论】:

        猜你喜欢
        • 2018-01-27
        • 1970-01-01
        • 2020-07-07
        • 2022-01-01
        • 2019-02-14
        • 2021-12-10
        • 2018-11-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多