react 引入图片

react 不支持img直接引入
<img src="../../images/img.png" alt="" />

第一种:使用import  **  from ' ......' 引入

import React from 'react';
import img from '../../images/img.png'

export default class Demo1 extends React.Component {
    constructor(props) {
        super(props)
        this.state = {

        }
    }

    render() {
        return (
            <div>
                引入图片
                <img src={img} alt=""/>
            </div>
        )
    }
}

第二种:使用require引入

import React from 'react';

export default class Demo1 extends React.Component {
    constructor(props) {
        super(props)
        this.state = {

        }
    }

    render() {
        return (
            <div>
                引入图片
                <img src={require("../../images/img.png")} alt="" />
            </div>
        )
    }
}

 如果是背景图

<div style={{ background: `url(${require("../../images/img.png")})` }}></div>

 网络图片: 

import React from 'react';

export default class Demo1 extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            img: "https://upload.jianshu.io/users/upload_avatars/13342447/38927c8e-f1ea-4b3f-a56a-440e304ce52b?imageMogr2/auto-orient/strip|imageView2/1/w/100/h/100/format/webp"
        }
    }

    render() {
        return (
            <div>
                引入图片
                <img src={this.state.img} alt="" />
            </div>
        )
    }
}


 ***  注意 使用img时候 需要些alt属性 如果不写会给出 警告  "img元素必须有alt属性,可以是有意义的文本,也可以是用于装饰图像的空字符串"

 

原文地址:https://www.cnblogs.com/chen-yi-yi/p/12845014.html