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