Как получить высоту и ширину изображения с помощью ReactJS?

Опубликовано: 23 Декабря, 2021

Реагируя на все, что мы пишем, похоже, что HTML на самом деле не является чистым HTML. Все, что выглядит как HTML, - это JSX, за кулисами они конвертируются в ванильный JavaScript с помощью babel. Все это работает таким образом, чтобы облегчить жизнь разработчикам. Поскольку JSX не является HTML, поэтому у нас есть прямая ссылка на элементы HTML и поэтому мы не можем напрямую получать свойства любого элемента HTML. Чтобы получить свойство элемента, React дает нечто, называемое «ref». Используя ref, мы можем создать прямую ссылку на любые элементы HTML и получить контроль над свойствами элементов HTML. Здесь мы используем систему ref для получения высоты и ширины изображения.

Пример 1. В этом примере показано, как получить текущую высоту и ширину изображения.

  • index.js:

    Javascript

    import React from 'react'
    import ReactDOM from 'react-dom'
    import App from './App'
    ReactDOM.render(<App />, document.querySelector( '#root' ))
  • App.js:

    Javascript

    import React, { Component } from 'react'
    class App extends Component{
    constructor(props){
    super (props)
    // Initialize count state
    this .state = {show : false }
    // Bind context of 'this'
    this .handleClick = this .handleClick.bind( this )
    // Create reference of DOM object
    this .imgRef = React.createRef()
    }
    renderDetails() {
    return this .state.show ?
    // Accessing image details using imgRef
    <div>
    <p><strong>Height : </strong>
    { this .imgRef.current.clientHeight}px</p>
    <p><strong>Width : </strong>
    { this .imgRef.current.clientWidth}px</p>
    </div> : null
    }
    handleClick(){
    // Update state value
    this .setState({
    show : true
    })
    }
    render(){
    return (
    <div>
    <h3>GeeksforGeeks</h3>
    { /* Assign reference to DOM element */ }
    <img ref={ this .imgRef} src=
    <div>
    <button onClick={ this .handleClick}>Get image details</button>
    </div>
    { this .renderDetails()}
    </div>
    )
    }
    }
    export App default

Выход :

Пример 2:

  • index.js:

    Javascript

    import React from 'react'
    import ReactDOM from 'react-dom'
    import App from './App'
    ReactDOM.render(<App />, document.querySelector( '#root' ))
  • App.js:

    Javascript

    import React, { Component } from 'react'
    class App extends Component{
    constructor(props){
    super (props)
    // Initialize count state
    this .state = {height: null , width: null , isIncrease: false }
    // Bind context of 'this'
    this .handleClick = this .handleClick.bind( this )
    // Create reference of DOM object
    this .imgRef = React.createRef()
    }
    handleClick(){
    // Fetching current height and width
    const height = this .imgRef.current.clientHeight
    const width = this .imgRef.current.clientWidth
    alert(`
    Height : ${height}
    Width : ${width}
    `)
    }
    render(){
    return (
    <div>
    <h3>GeeksforGeeks</h3>
    { /* Assign reference to DOM element */ }
    <img ref={ this .imgRef} src=
    <div>
    <button onClick={ this .handleClick}>
    Fetch dimension
    </button>
    </div>
    </div>
    )
    }
    }
    export App default

Выход :