反应-获取要处理的图像的宽度/高度 [英] react - get width/height of image to process

查看:60
本文介绍了反应-获取要处理的图像的宽度/高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如果渲染图像时要如何获得图像的高度和宽度,以便在宽度大于高度时将其翻转为纵向模式。

I was wondering how to get the height and width of an image if I'm rendering it react style so I can process it to flip it to portrait mode if the width is larger than the height.

示例: https://codesandbox.io/s/k9kwv0kp93

示例代码:

index.js

import React from 'react';
import { render } from 'react-dom';
import Hello from './Hello';

const styles = {
  fontFamily: 'sans-serif',
  textAlign: 'center',
};

const App = () => (
  <div style={styles}>
    <Hello name="CodeSandbox" />
    <h2>Start editing to see some magic happen {'\u2728'}</h2>
  </div>
);

render(<App />, document.getElementById('root'));

Hello.js

import React, {Component} from 'react';

export default class Hello extends Component
{
  constructor()
  {
    super();
    this.state = {img: null}

    this.get_image = this.get_image.bind(this);
  }

  get_image() 
  {
    let img = <img src="http://via.placeholder.com/350x150" alt="" />;
    //manipulate here maybe
    this.setState({
      img
    })
  }

  render()
  {
    return (
      <div>
        <button onClick={this.get_image}>Click me</button>
        test
        {this.state.img}
      </div>
    )
  }
}


推荐答案


React支持可以附加到任何组件的特殊属性。 ref属性具有回调函数,在挂载或卸载组件后立即执行回调。

React supports a special attribute that you can attach to any component. The ref attribute takes a callback function, and the callback will be executed immediately after the component is mounted or unmounted.

在HTML元素上使用ref属性时,ref回调将收到底层DOM元素作为其参数

When the ref attribute is used on an HTML element, the ref callback receives the underlying DOM element as its argument

来自: https://facebook.github.io/react/docs/refs-and-the-dom.html

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
  }

  handleSize(image) {
    console.log(image.offsetWidth, image.offsetHeight)
  }

  render() {
    return React.createElement("img", {
      src: "http://cdn.collider.com/wp-content/uploads/2016/07/narcos-season-2-image-5.jpg",
      ref: image => {
        this.handleSize(image);
      },
      onLoad=(image)=>this.handleSize(image);
    });
  }
}

ReactDOM.render(React.createElement(MyComponent, null), document.getElementById('root'))

img {
  width: 200px;
  height: 133px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-with-addons.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>

这篇关于反应-获取要处理的图像的宽度/高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆