2016-11-19 22 views
3

我嘗試構建此Web應用程序時第一次嘗試React.js。我在下面指定的行上獲得Cannot read property 'setState' of null。我一直試圖弄清楚爲什麼在過去的幾個小時內,似乎無法弄清楚。任何幫助將不勝感激。無法讀取屬性'setState'null - React.js,Modal,Bootstrap

MyModal.jsx

import React from 'react'; 
import { Modal, Button, ButtonToolbar } from 'react-bootstrap'; 

export default class MyModal extends React.Component { 
    constructor(props) { 
     super(props); 
     this.state = {show: false}; 
    } 

    showModal() { 
     this.setState({show: true}); 
    } 

    hideModal() { 
     this.setState({show: false}); 
    } 

    render() { 
     return (
     <ButtonToolbar> 
      <Button bsStyle="primary" onClick={this.showModal}> 
      Launch demo modal 
      </Button> 

      <Modal 
      {...this.props} 
      show={this.state.show} 
      onHide={this.hideModal} 
      dialogClassName="custom-modal" 
      > 
      <Modal.Header closeButton> 
       <Modal.Title id="contained-modal-title-lg">Modal heading</Modal.Title> 
      </Modal.Header> 
      <Modal.Body> 
       <h4>Wrapped Text</h4> 
       <p>Blah</p> 
      </Modal.Body> 
      <Modal.Footer> 
       <Button onClick={this.hideModal}>Close</Button> 
      </Modal.Footer> // Chrome inspector says it errors on this line 
      </Modal> 
     </ButtonToolbar> 
     ); 
    } // end render function 

} // end export default 

回答

8

綁定您的組件類的方法裏面的constructor()(內部構造結合比對性能的緣故內render()結合更好):

constructor(props) { 
    super(props); 
    this.state = {show: false}; 
    this.showModal = this.showModal.bind(this); 
    this.hideModal = this.hideModal.bind(this); 
} 
+0

哦,太好了!我也發佈了一個解決方案,但我更喜歡你的,所以我會刪除我的。 – noblerare

+0

我們不希望'.bind'在每個渲染器上創建一個新函數:) –

+1

這完全解決了我的問題,但合理的問題是爲什麼這個樣板文件首先是必需的,爲什麼沒有辦法自動執行此操作用較少的代碼手寫,相反,我很樂意爲我完成這個工作,所以我不能把它搞砸,並把它排除在外。一個真正的失望。可能的答案:是因爲* constructor()*在我的組件的「靜態」類中,而不是實例方法。蹩腳的「懲罰程序員」API設計。 –