在加载另一个图像后如何将图像添加到DOM?

时间:2016-12-22 16:32:49

标签: reactjs

我想确保以正确的顺序加载图像:首先是主图像,然后是次图像。我的计划是在主映像完成后注入secondaryImage。

class HoverImage extends Component {
  constructor (props) {
    super(props)
    this.state = { secondaryImage: null }
  }

  primaryImageLoaded () {
    //here I would like inject <img className='img-responsive' src={stripUrl(secondaryImage)} /> before primaryImage
  }

  render () {
    const primaryImage = this.props.primaryImage
    const secondaryImage = this.props.secondaryImage
    if (secondaryImage) {
      return (
        <div style={{position: 'relative'}}>
          <img
            className='img-responsive'
            src={stripUrl(primaryImage)}
            onLoad={this.primaryImageLoaded.bind(this)}
            style={{
              ':hover': {
                opacity: 0
              },
              position: 'absolute',
              top: 0}}
            />
        </div>
      )
   }
}

其他产生相同效果的解决方案也很好!

2 个答案:

答案 0 :(得分:0)

class HoverImage extends Component {
  constructor (props) {
    super(props)
    this.state = {
        firstImageLoaded: false,
    };
  }

  componentDidMount() {
     this.setState({ firstImageLoaded: true });
  }

  loadSecondImage() {
    if(this.state.firstImageLoaded) {
        return  (<img
            className='img-responsive'
            src={stripUrl(this.props.secondaryImage)}
            />);
    }
  }

  render () {
      return (
        <div style={{position: 'relative'}}>
            <img
            className='img-responsive'
            src={stripUrl(this.props.primaryImage)}
            onLoad={this.setState({ firstImageLoaded: true })}
            style={{
              ':hover': {
                opacity: 0
              },
              position: 'absolute',
              top: 0}}
            />
            {this.loadSecondImage()}
        </div>
      )
}

初始安装完成后,它将在触发重新渲染的状态下设置一个标志。

希望有所帮助!

ps:这个答案绝不是完美的,但应该得到你想做的事。

答案 1 :(得分:0)

试试这个:

  <?php  
        if( !empty($obtOpera)) {
         foreach($obtOpera as $fi) { 
           if( !empty($consult) ) {
             foreach($consult as $fil) {
               if($fil->operation==$fi->operation && $fila->cveEmp ==$fil->cveEmp)  { 

                echo "<td class='$fil->color'<h4> $fil->operation</h4> X";
               }#Close if
            elseif ($fi->operation!=$fil->operation) {
             echo "<td>N/A</td>";

          }#Close Else if
        }#Close consult 
      }#Close if that compare operation
     }#Close foreach fi 
   }#Close if de obtOpera  ?>

jsfiddle链接:http://jsfiddle.net/d7hwzapc/

相关问题