【问题标题】:Get exact width and height of images in react在反应中获取图像的确切宽度和高度
【发布时间】:2017-08-22 22:07:15
【问题描述】:

我是新来的反应。 我有一组由file-loader 插件加载的图像。我像这样映射它们:

images.map((img, index) => <img src={img}>

如何获取每张图片的宽度和高度属性?我知道如何设置属性,但我不知道图像的高度和宽度,因为它们在数组中。

【问题讨论】:

  • 高度和宽度基于什么?就像页面的样式表有 img { height: 40px; } 一样,这会影响这个值,还是你在谈论实际图像大小,因为它看起来是 100% 缩放?并让它在render 函数中或稍后使用?
  • @loganfsmyth 是的,我需要实际的图像大小,是的,我想在渲染函数中使用它们。

标签: reactjs image ecmascript-6


【解决方案1】:

您可以使用image-size-loader 之类的内容进行探索。 file-loader 不提供您正在寻找的行为。

【讨论】:

  • 这就是我想要的。它是否能够设置 outputPath 和其他文件加载器选项?
  • 我还发现了image-size,它只是用于获取图像大小。
  • 您必须查看文档以获取选项,我不知道。加载程序 uses image-size 在其内部。
【解决方案2】:

你可以通过 onLoad 属性获取数据

class ImgLoader extends Component {
  constructor(props) {
    super(props);
    this.state = {
      error: false,
    };
  }

  onImgLoad = ({ target: img }) => {
    this.setState({
      width: img.width,
      height: img.height,
    });
  };

  onImgError = e => {
    e.target.src = '/path/no-picture.jpg';
    this.setState({
      error: true,
    });
  };

  render() {
    const { image, alt } = this.props;
    const { width, height, error } = this.state;
    console.log(width, height, error);
    return <img onLoad={this.onImgLoad} src={image} alt={alt} onError={this.onImgError} />;
  }
}

【讨论】:

    【解决方案3】:

    方法有很多种,前端世界仍然存在争论哪种方法最好。以下是帮助您入门的两种简单方法。

    内嵌样式

    <img style={{width: '50px', height: '50px'}} src={img} />
    

    简单的 CSS

    import './MyCSSFileName'
    
    <img className="fixed_img" src={img} />
    
    // in your .css file
    .fixed_img {
      width: 50px;
      height: 50px;
    }
    

    【讨论】:

    • 其实我的问题是我应该如何得到宽度和高度
    猜你喜欢
    • 1970-01-01
    • 2010-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-08
    • 2018-05-06
    • 2012-09-14
    • 1970-01-01
    相关资源
    最近更新 更多