【问题标题】:PropTypes for NextJS Image ComponentNextJS 图片组件的 PropTypes
【发布时间】:2021-04-11 12:11:33
【问题描述】:

我将新的Next.js Image component 包含在另一个组件中,如下所示:

import PropTypes from "prop-types";
import Image from "next/image";

const Pattern = ({ classes, src, alt, width, height, layout }) => (
  <div className={classes.wrapper}>
    <Image
      src={src}
      alt={alt}
      width={width}
      height={height}
      layout={layout}
      className={classes.img}
    />
  </div>
);

Pattern.propTypes = {
  classes: PropTypes.shape({
    wrapper: PropTypes.string,
    img: PropTypes.string,
  }),
  src: PropTypes.string,
  alt: PropTypes.string,
  layout: PropTypes.string
};

export default Pattern;

如您所见,我们使用的是prop-types。我无法弄清楚要为宽度和高度设置什么道具类型。以下是 Next.js 文档中 Image 组件的示例用法:

<Image
  src="/me.png"
  alt="Picture of the author"
  width={500}
  height={500}
/>

我不确定如何设置。 PropTypes.number? PropTypes.object?还有什么?

【问题讨论】:

    标签: reactjs next.js react-proptypes nextjs-image


    【解决方案1】:

    尝试使用字符串和 isRequired

    Pattern.propTypes = {
      width: PropTypes.number.isRequired,
    }
    

    【讨论】:

      【解决方案2】:

      在您的文档链接中,如果您滚动到所需的道具,它会说它必须是整数,对于 width 和/或 height

      图像的宽度,以像素为单位。必须是没有单位的整数

      鉴于此,PropTypes.number 将是两者的正确 PropType。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-10-17
        • 2018-09-17
        • 1970-01-01
        • 2019-11-29
        • 1970-01-01
        • 2022-12-30
        • 2021-09-14
        • 2021-09-18
        相关资源
        最近更新 更多