将 props 传递给 TS 中的 makeStyle

thi*_*ras 5 typescript reactjs material-ui next.js

如何传递post.mainImagebackgroundImage风格。

这是我的代码;

import React from 'react';
import { Post } from '../interfaces';
import { makeStyles, createStyles, Theme } from '@material-ui/core/styles';
import Container from '@material-ui/core/Container';

type Props = {
  post: Post;
}

const useStyles = makeStyles<Theme, Props>((theme: Theme) =>
  createStyles({
    root: {
      maxWidth: '100%',
      backgroundImage: ({ post }) => post.mainImage
    },
    date: {
      margin: theme.spacing(1),
      marginLeft: theme.spacing(2)
    },
    heroimage: {
      maxWidth: '100%',
      height: 'auto',
      objectFit: 'cover'
    }
  })
);

export default function HeroPost({ post }: Props) {
  const classes = useStyles({ post });
  return (
    <Container className={classes.root}>
      <img alt={post.title} src={post.mainImage} className={classes.heroimage} />
    </Container>
  );
}
Run Code Online (Sandbox Code Playgroud)

下面的代码已经通过 linter 没有问题。但是还是拿不到backgroundImage前面的值。

Lio*_*owe 22

您可以为调用提供类型变量makeStyles(请注意,第一个必须是主题类型,第二个必须是道具类型):

type Props = {
  post: Post;
};

const useStyles = makeStyles<Theme, Props>(theme =>
  createStyles({
    root: {
      maxWidth: '100%',
      backgroundImage: ({ post }) => `url("${post.mainImage}")`
    },
    // ...
  })
);

export default function HeroPost({ post }: Props) {
  const classes = useStyles({ post });

  return (
    // ...
  );
}
Run Code Online (Sandbox Code Playgroud)