2017-04-06 97 views
0

當我嘗試運行下面的代碼時,我在控制檯「Can not read property'state of undefined」中看到錯誤。我相信它與使用this.有關,但我不知道如何解決它。我使用這裏的快速入門示例:https://github.com/jossmac/react-images。誰能幫忙?React LightBox(react-images):無法讀取未定義的屬性'狀態'

ReactDOM.render(

      <div> 
      <Lightbox 
      images={[{ src: 'http://example.com/img1.jpg' }, { src: 'http://example.com/img2.jpg' }]} 
      isOpen={this.state.lightboxIsOpen} 
      onClickPrev={this.gotoPrevious} 
      onClickNext={this.gotoNext} 
      onClose={this.closeLightbox} 
      /> 



      </div>, 
      document.getElementById("contents") 
     ) 
+0

該錯誤有點不言自明。你有沒有試過把這個jsx代碼放入一個反應組件,並讓它使用ReactDOM渲染? – kasperite

+0

將'this.state.lightboxIsOpen'更改爲'true'並移除'onClickPrev','onClickNext'和'onClose'。你沒有使用這些,所以不要從示例中複製它們。 – Aaron

+0

@Aaron啊,我明白了。另一個問題,如果我要定義LightboxIsOpen,gotoPrevious,gotoNext,closeLightbox,我在哪裏定義它? – intangibles

回答

0

您應該創建一個React Component並定義其所有屬性。然後,您可以使用ReactDOM.render()來渲染該組件,如

class App extends React.Component { 
    constructor() { 
    super(); 
    this.state = { 
     lightboxIsOpen: true 
    } 
    this.gotoPrevious = this.gotoPrevious.bind(this); 
    this.gotoNext = this.gotoNext.bind(this); 
    this.closeLightbox = this.closeLightbox.bind(this); 
    } 
    gotoPrevious() { 
    //....body here 
    } 
    gotoNext() { 
    //..body here 
    } 
    closeLightbox() { 
    //..body here 
    } 
    render() { 
    return (
     <div> 
      <Lightbox 
      images={[{ src: 'http://example.com/img1.jpg' }, { src: 'http://example.com/img2.jpg' }]} 
      isOpen={this.state.lightboxIsOpen} 
      onClickPrev={this.gotoPrevious} 
      onClickNext={this.gotoNext} 
      onClose={this.closeLightbox} 
      /> 

     </div> 
    ) 
    } 
} 

ReactDOM.render(
     <App/>,document.getElementById("contents") 
     ) 
+0

感謝你們,我能夠理解我應該把構造函數放在哪裏並定義函數。如何從Lightbox燈箱內以縮略圖形式呈現圖像?我在div中調用了this.renderGallery(),但我不知道如何定義函數以從Lightbox中將圖像拉到縮略圖顯示。 – intangibles

相關問題