2015-12-04 19 views
6

Ho un componente di reazione che è la vista di dettaglio da un elenco.react.js Sostituisci img src onerror

Sto cercando di sostituire l'immagine con un'immagine predefinita se l'immagine non esiste e c'è un errore 404.

Normalmente utilizzerei il metodo onerror nel tag img ma non sembra funzionare.

Non sono sicuro di come farlo con reagire.

Qui è la mia componente:

import React from 'react'; 
import {Link} from 'react-router'; 
import ContactStore from '../stores/ContactStore' 
import ContactActions from '../actions/ContactActions'; 

class Contact extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = ContactStore.getState(); 
    this.onChange = this.onChange.bind(this); 
} 

componentDidMount() { 
    ContactStore.listen(this.onChange); 
    ContactActions.getContact(this.props.params.id); 
} 

componentWillUnmount() { 
    ContactStore.unlisten(this.onChange); 
} 

componentDidUpdate(prevProps) { 
    if (prevProps.params.id !== this.props.params.id) { 
    ContactActions.getContact(this.props.params.id); 
    } 
} 

onChange(state) { 
    this.setState(state); 
} 

render() { 
    return (
    <div className='container'> 
     <div className='list-group'> 
     <div className='list-group-item animated fadeIn'> 
      <h4>{this.state.contact.displayname}</h4> 
      <img src={this.state.imageUrl} /> 
     </div> 
     </div> 
    </div> 
); 
} 
} 

export default Contact; 
+0

mi sono imbattuto in questo problema, e non ho il codice per assistere al momento, ma quello che ho fatto è stato posto il check-in javascript componentdidmount, che cerca un errore di immagine, se si verificano, viene attivato un callback che sostituisce quell'immagine con l'immagine predefinita. –

risposta

1

è necessario solo definire gestore onError di cambiare lo stato che attiverà componente metodo Render e alla fine componente ri-renderizzare con segnaposto.

Per favore, non usare jQuery e Reagire insieme!

import React from 'react'; 
import {Link} from 'react-router'; 
import ContactStore from '../stores/ContactStore' 
import ContactActions from '../actions/ContactActions'; 

class Contact extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = ContactStore.getState(); 
    this.onChange = this.onChange.bind(this); 
} 

componentDidMount() { 
    ContactStore.listen(this.onChange); 
    ContactActions.getContact(this.props.params.id); 
} 

componentWillUnmount() { 
    ContactStore.unlisten(this.onChange); 
} 

componentDidUpdate(prevProps) { 
    if (prevProps.params.id !== this.props.params.id) { 
    ContactActions.getContact(this.props.params.id); 
    } 
} 

onChange(state) { 
    this.setState(state); 
} 

onError() { 
    this.setState({ 
    imageUrl: "img/default.png" 
    }) 
} 

render() { 
    return (
    <div className='container'> 
     <div className='list-group'> 
     <div className='list-group-item animated fadeIn'> 
      <h4>{this.state.contact.displayname}</h4> 
      <img onError={this.onError.bind(this)} src={this.state.imageUrl} /> 
     </div> 
     </div> 
    </div> 
); 
} 

export default Contact; 
2

ho preso @ risposta di Skay e ha creato un componente Immagine riutilizzabile. Distacco in caso aiuta chiunque:

import React, { PropTypes } from 'react'; 
 

 
const Image = ({src, fallbackSrc, ...other}) => { 
 
    let element; 
 
    const changeSrc = newSrc => { 
 
     element.src = newSrc; 
 
    }; 
 
    return (
 
     <img src={src} 
 
      onError={() => changeSrc(fallbackSrc)} 
 
      ref={el => element=el} 
 
      {...other} /> 
 
    ); 
 
}; 
 

 
Image.propTypes = { 
 
    src: PropTypes.string, 
 
    fallbackSrc: PropTypes.string 
 
}; 
 
export default Image;

+0

Non si dovrebbe memorizzare lo stato nel componente '' ', ma piuttosto nel componente' ', che significherebbe refactoring come componente stateful e usando qualcosa come this.setState ({src: defaultSrc})'. –

5

È possibile utilizzare componente incontrollata:

<img src={this.state.img} ref={img => this.img = img} onError={ 
    () => this.img.src = 'img/default.img' 
}> 
+0

Grazie, funziona per me! Perché la risposta non è accettata? – Aitor

0

Ecco come ho fatto.

class Pix extends React.Component{ 

      constructor(props){ 
      super(props); 
      this.state={link: this.props.link}; 
      this.onError=this.onError.bind(this); 
      } 


      onError(){ 
       console.log("error: could not find picture"); 
       this.setState(function(){ return {link: "missing.png"}; }); 
      }; 

      render(){ 
      return <img onError={this.onError} src={this.state.link}/>; 
      } 
    } 
5

Questo funziona meglio per me

<img src={record.picture} onError={(e)=>{e.target.src="image_path_here"}}/> 
+0

Bello e semplice! –

Problemi correlati