之前我使用过其他的React组件,它们大多都有自己的Image组件,但是在Material-UI中我找不到它?
是通过CardMediaAPI完成的吗?还是只需使用标签即可?谢谢!
之前我使用过其他的React组件,它们大多都有自己的Image组件,但是在Material-UI中我找不到它?
是通过CardMediaAPI完成的吗?还是只需使用标签即可?谢谢!
<Box
component="img"
sx={{
height: 233,
width: 350,
maxHeight: { xs: 233, md: 167 },
maxWidth: { xs: 350, md: 250 },
}}
alt="The house from the offer."
src="https://images.unsplash.com/photo-1512917774080-9991f1c4c750?auto=format&w=350&dpr=2"
/>
在Material-UI中没有这种特定的自定义图像组件。
但是,您可以使用简单的HTML img组件放置在其他封装组件中,自己创建自定义的img组件。例如:
<Paper variant="outlined">
<img src="url" />
</Paper>
同时,<CardMedia/>
组件必须与 <Card/>
组件一起使用。
另一个使用图片的组件是 <Avatar>
组件。
<Avatar alt="Example Alt" src="/static/images/avatar.jpg" />
Material-ui 推荐 使用 Material-ui-image,但需要单独安装,不过我使用它的体验非常愉快。 安装后,使用起来很简单:
import Image from "material-ui-image";
...
<Image src="image/src/" />
使用 MUI 的 Box 组件是一个好的起点。从那里开始,您可以轻松构建自己的可重复使用组件,而无需依赖其他组件。尝试像这样做:
import {Box, BoxProps, } from "@mui/material";
type ImgProps = {
alt: string;
src: string;
// add more HTML img attributes you need
}
export const Img = (props: BoxProps & ImgProps) => <Box component='img' {...props} />;
当我回答这个问题时,最新版本的 MUI
是 5.2.2
,没有确切的图像组件,但 MUI
提到了两个由第三方提供的 图像 组件。一个是 mui-image,另一个是material-ui-image。根据 MUI 的说法,“mui-image
是唯一满足 Material 指南加载图像的 MUI 图像组件”。
按照以下步骤,您可以轻松安装 mui-image
:
安装:
npm i mui-image
//or
yarn add mui-image
导入:
import Image from 'mui-image'
// or
import { Image } from 'mui-image'
用途:
<Image src="my-image.png" />
欲了解关于 mui-image
props
等详细信息,请查看 npmjs
包文档,此处。
我更喜欢使用styled
来创建自己的图像组件:
import { styled } from '@mui/material/styles';
const StyledImg = styled('img')({});
// Or with a default style
// const StyledImg = styled('img')({
// display: 'block',
// });
<StyledImg
src={imagePath}
alt='my Image'
sx={{
width: 50,
}}
/>
使用组件属性与 Box 组件:
<Box component="img" src={image} alt={caption} sx={{ height: "50px", width: "auto" }} />
使用Avatar
组件
<Avatar variant={"rounded"} alt="The image" src={url} style={{
width: 200,
height: 200,
}} />
<CardMedia
className={classes.media}
image="/static/images/cards/paella.jpg"
title="Paella dish"
/>
const [previewImage, setPreviewImage]= useState<any>();
const { getRootProps, getInputProps } = useDropzone({
accept: "image/*",
onDrop: (acceptedFiles) => {
setPreviewImage(URL.createObjectURL(acceptedFiles[0]));
},
});
<CardMedia
component="img"
sx={{
height: 233,
width: 350,
maxHeight: { xs: 233, md: 167 },
maxWidth: { xs: 350, md: 250 },
}}
src={previewImage}
/>