React 中的影象標籤

Rana Hasnain Khan 2024年2月15日
React 中的影象標籤

我們將介紹如何在 React 中新增影象。

React 中的影象標籤

首先,我們將在 index.html 檔案中新增一個類 rootdiv

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

index.tsx 檔案中,我們將定義影象的 nameurltitle

# react
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';

interface AppProps { }
interface AppState {
  name: string;
  url: string;
  title: string;
}

class App extends Component<AppProps, AppState> {
  constructor(props) {
    super(props);
    this.state = {
      name: 'React',
      url: 'https://images.pexels.com/photos/8549835/pexels-photo-8549835.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
      title: "Vase Image"
    };
  }

  render() {
    return ();
  }
}

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

我們已經拍攝了一張示例照片。現在我們將通過在影象標籤中傳遞值來返回影象。

# react
<div>
           <img src={this.state.url} alt={`${this.state.title}'s picture`}  className="img-responsive" />
           <span>Hello {this.state.name}</span>
        </div>

因此,我們在 index.tsx 中的程式碼將如下所示。

# react
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';

interface AppProps { }
interface AppState {
  name: string;
  url: string;
  title: string;
}

class App extends Component<AppProps, AppState> {
  constructor(props) {
    super(props);
    this.state = {
      name: 'React',
      url: 'https://images.pexels.com/photos/8549835/pexels-photo-8549835.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
      title: "Vase Image"
    };
  }

  render() {
    return (
      
      <div>
           <img src={this.state.url} alt={`${this.state.title}'s picture`}  className="img-responsive" />
           <span>Hello {this.state.name}</span>
        </div>
    );
  }
}

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

讓我們新增一些 CSS 程式碼來調整我們的影象大小。

# react
.img-responsive{
  width: 90vw;
}

輸出:

React 影象標籤

我們現在可以看到我們已經在 React 中輕鬆新增了影象。

Rana Hasnain Khan avatar Rana Hasnain Khan avatar

Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.

LinkedIn

相關文章 - React Image