在 TS 中将 props 传递给 makeStyle [英] Passing props to the makeStyle in TS

查看:94
本文介绍了在 TS 中将 props 传递给 makeStyle的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 post.mainImage 传递给 backgroundImage 样式.

How can I pass post.mainImage to backgroundImage style.

这是我的代码;

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>
  );
}

下面的代码通过 linter 没有问题.但是还是无法获取到前面的backgroundImage值.

The code below has passed without a problem from the linter. But still cannot get the backgroundImage value on the front.

推荐答案

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

You can supply type variables to the call to makeStyles (note that the first one must be the theme type and the second the prop type):

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 (
    // ...
  );
}

这篇关于在 TS 中将 props 传递给 makeStyle的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆