简体   繁体   中英

Create a dynamic height width image component in react

I am trying to create a dynamic image component which will be using a material-ui CardMedia and will pass only height and width.

I have following code

interface ImageDim extends StyledProps {
  width: number,
  height: number
}

const MediaImage = styled.img`
  width: ${props => props.width}px;
  height: ${props => props.height}px;
  object-fit: contain;
`;

export const BuyingImage  = () => {
  return (
    <CardMedia
      alt={'IMAGE'}
    />
  )
} 

I am calling this from somewhere else like

<BuyingImage />

Can anyone help me with this? Thanks

First, kindly checkout Material-UI Card document , since CardMedia is used inside a Card , and the prop for url is image not alt

As for dynamic height and width, simply pass the value as props seem to work good enough.

在此处输入图片说明

export default function App() {
  return <Image size={{ width: 400, height: 200 }} />;
}

const Image = props => {
  const width = props.size.width;
  const height = props.size.height;
  return (
    <Card
      style={{
        width: `${width}px`,
        height: `${height}px`
      }}
    >
      <CardMedia
        className="media"
        image={`https://via.placeholder.com/${width}x${height}`}
      />
    </Card>
  );
};

You can try it yourself here:

编辑currying-lake-q6ipu

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM