在TS中将道具传递给makeStyle

时间:2020-09-05 23:36:51

标签: reactjs typescript material-ui next.js

如何将post.mainImage传递给backgroundImge样式。

这是我的代码;

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值。

5 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:0)

您可以像这样访问道具

backgroundImage: props => props.backgroundImageProp

https://material-ui.com/styles/api/#returns-3

答案 2 :(得分:0)

尝试一下:useStyles是一个钩子,可以在参数中使用props并返回方法useStyles。

const useStyles = (props: Props) => {
       const {post} = props;
    
       return makeStyles(theme => ({
           root: {
              maxWidth: '100%',
              backgroundImage: post.mainImage
           },
      }))
    } 

答案 3 :(得分:0)

使用Typescript尝试一下:

   const useStyles = makeStyles(theme => ({
           root: ({mainImage}: {mainImage: string}) => ({
                 ...
                 backgroundImage: mainImage
           })        
    })
        
    const component: React.FC => {
        const classes = useStyles({mainImage})
         return ...
    }

答案 4 :(得分:0)

你需要直接在你想访问它的地方传递它的类型。这应该可以正常工作。

type BgProps = {
  mainImage: string;
}

const useStyles = makeStyles<Theme, Props>((theme: Theme) =>
  createStyles({
    root: {
      maxWidth: '100%',
      backgroundImage: (props: BgProps) => props.mainImage
    },
    date: {
      margin: theme.spacing(1),
      marginLeft: theme.spacing(2)
    }
  })
);