首页 > 解决方案 > ReactJS:如何从状态动态添加 JSX IMG SRC 参数?

问题描述

我不知道如何在 ReactJS 中动态加载 img src。

当用户浏览页面时,我正在从一个 json 文件更新状态,其中包括来自 json 的英雄图像和 alt 标签。alt 属性工作正常,但我一直在尝试img src=""动态加载但没有任何成功。

我在这里看到了一个我们使用require和模板文字的解决方案,但这对我不起作用,见下文:

<img src={require(`${this.state.activePageData.url}`)}

此代码返回错误“找不到未定义的模块”。

根据这里的一些帖子,我应该删除 node_modules 文件夹并运行npm install,我也这样做了,但没有任何结果。

如果我尝试直接使用状态(<img src={this.state...} />)它会呈现页面但未加载图像,如果我检查元素,则在开发工具上,它在已编译 HTML 的源元素中具有正确的路径,但它没有渲染图像。在网络选项卡上,它返回一个具有正确图像名称和状态 200 OK 的元素,但单击此元素时不会在应用程序选项卡上显示图像。

我是 ReactJS 的新手,对它了解不多。我试图使用调试器来解决这个问题,但不能。有人能伸出援手吗?谢谢你。

import React, {Component} from 'react';
import propTypes from 'prop-types'
import PageData from '../PageInfo.json';

class Hero extends Component {
  state = {
    activePage: '',
    activePageData: [],
    PageData: PageData
  }

componentDidMount = () => {
 switch (this.props.page) {
   case 'homepage':
    this.setState({activePage: ''})
    this.setState({activePage: this.props.page})
    this.getBackgroundImage('Homepage')
    break;
  case 'about':
    this.setState({activePage: ''})
    this.setState({activePage: this.props.page})
    this.getBackgroundImage('About')
    break;
  default:
    console.log("There's no such page")
    break;
  }
}

 getBackgroundImage = (page) => {
   this.state.PageData.Pages.forEach( e => {
     if ( e.PageName === page ) {
       this.setState({activePageData: ''})
       this.setState({activePageData: e }, () => {
       })
     }
   })
  }

render() {

 const styles = {
   bgStyle: {
     height: '100vh',
     width: 'auto',
     position: 'absolute',
     zIndex: '1',
     background: '#074481',
     backgroundSize: 'cover',
     backgroundPosition: '50% 50%'
  },
  imgStyle: {
    height: '100%',
    width: 'auto'
  }
}

return(
  <section className="cover fullscreen image-bg parallax">
      <div style={styles.bgStyle}>
        <img alt={this.state.activePageData.alt} style={styles.imgStyle} src={this.state.activePageData.url} /> </div>
      <div className="container v-align-transform">
          <div className="row">
              <div className="col-sm-12">
                  <h1 className="col-sm-12 large">Header</h1>
                  <h2 className="pl20">Title 2</h2>
          </div>
      </div>
    </div>
   </section>
  )
 }
}
Hero.propTypes = {
  page: propTypes.string.isRequired
}

export default Hero

抱歉,这是 JSON:

{
  "Pages": [
     {
       "id": 1,
       "title": "Home Page Title",
       "PageName": "Homepage",
       "url": "../img/hero-home.jpg",
       "alt": "alt text test",
       "description": "Home page desc test"
     },
     {
       "id": 2,
       "title": "About Page Title",
       "PageName": "About",
       "url": "../img/about-hero.jpg",
       "alt": "About Alt text",
       "description": "About page desc test"
     }
   ]
 }

编辑:请注意组件 Hero 位于组件目录中,该目录需要图像的路径为 ../

标签: reactjs

解决方案


我认为它在您的 img 文件夹路径中。../img/ 会将文件夹放在公用文件夹之外

我让它工作:

  • 用你的名字将图片放在我的 public/img 文件夹中(hero-home.jpg / about-hero.jpg)
  • 将 ../img 更改为 ./img

希望有帮助。


推荐阅读