反应 - 获取要处理的图像的宽度/高度

时间:2017-09-04 04:03:05

标签: javascript css reactjs

我想知道如果我正在渲染图像的高度和宽度如何反应样式,所以如果宽度大于高度,我可以处理它以将其翻转为肖像模式。

示例: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>
    )
  }
}

2 个答案:

答案 0 :(得分:5)

我遇到了同样的问题,我能够使用imgref获得onLoad()的高度和宽度。


类组件版本(使用“旧”引用):


render() {
   return (
     <img
        src='https://via.placeholder.com/150'
        ref={el => this.imgEl = el}
        onLoad={() => console.log(this.imgEl.naturalHeight)} // print 150
     /> 
  )
}

类组件版本(带有“ new”参考):

https://codesandbox.io/s/xjv82px81q

import * as React from "react";
import ReactDOM from "react-dom";

class App extends React.Component {
  imgEl = React.createRef();

  render() {
    return (
      <img
        src="https://via.placeholder.com/150"
        ref={this.imgEl}
        onLoad={() => console.log(this.imgEl.current.naturalHeight)} // print 150
      />
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

功能组件版本:

https://codesandbox.io/s/k0mnnk5p07

import React from "react";
import ReactDOM from "react-dom";

function App() {
  const imgElement = React.useRef(null);

  return (
    <img
      src="https://via.placeholder.com/150"
      ref={imgElement}
      onLoad={() => console.log(imgElement.current.naturalHeight)} // print 150
    />
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

还应该使用img.naturalHeight

答案 1 :(得分:3)

  

React支持可以附加到任何组件的特殊属性。 ref属性采用回调函数,并且在安装或卸载组件后立即执行回调。

     

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

取自: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);
      }
    });
  }
}

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>