我的图片元素和React

时间:2017-03-29 05:16:55

标签: javascript reactjs

好吧,嘿伙计们。试图让这个时钟与图片一起运作。我不仅仅是那个,但如果我能弄明白,我可以处理其他人。经过多次搜索,我发现你不能在一个属性中使用字符串插值,但我保留它以显示我尝试过。我认为第二个应该工作"并且它显示变量i尝试或pic0,pic1等等但是它不是实际模块我在顶部导入的实际模块(在实际的应用程序中我将它们全部导入但是切断为了简洁起见,他们失望了。任何帮助?我抨击了导致这个问题的原因

import React, { Component } from 'react';
import './App.css';
import './bootstrap-3.3.7-dist/css/bootstrap.min.css';
import pic0 from './0.png';

export default class Clock extends Component {
  constructor(props) {
    super(props);
    this.incrementTime = this.incrementTime.bind(this);
    this.dayInWords = this.dayInWords.bind(this);
    this.state = {
      clock: new Date(),
      day: (new Date()).getDay(),
      hours0: 0,
      minutes0: 0,
      seconds0: 0,
      hours1: 0,
      minutes1: 0,
      seconds1: 0
    }
  }


  componentWillMount() {
    let intervalTimer = setInterval(this.incrementTime, 1000);
  }

  componentWillUnmount() {
    clearInterval(this.state.intervalTimer);
  }

  incrementTime() {
    this.setState(currentState => {
      return {
        clock: new Date(),
        seconds1: ((new Date()).getSeconds())%10
      };
    });
  }
  render() {
    return(
        <div className='panel-body imgContainer'>
          <img src={pic0} alt='the digit 0' />
          <p>Know this one doesnt work but kept here to show I tried it</p>
          <img src={`pic${this.state.seconds1}`} alt='seconds1' />

          <p>I think this should work and the src is what I want as the variable that im importing at the top but its just a string not the variable.</p>
          <img src={'pic' + this.state.seconds1} alt='seconds1' />

          <p>This is the end goal im trying to accomplish but im trying to see if it can be done using this.state.seconds so its kind of "dynamic" and the source changes every second thus changing the image</p>
          <img src={pic0} alt='seconds1' />
        </div>
        );
      }
    }

这就是我所看到的,未显示src的图像是&#34;变量&#34;我在顶部导入,但它实际上没有调用该变量/模块对不起,如果我的术语是错误的,我显然很新。

enter image description here

感谢所有的帮助!!!!

1 个答案:

答案 0 :(得分:1)

虽然评论中澄清了这一点,但对于这篇文章的未来访问者 - 您需要直接引用导入的图像:

import pic from './myImage';

// works
<img src={ pic } />

它可以放在状态或其他变量中,但不能通过具有相同名称的字符串访问:

// Doesn't work
<img pic={ 'pic' } />