2017-04-06 64 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

相关问题