2016-11-19 12 views
3

私はReact.jsを初めてこのWebアプリケーションを構築しようとしています。私は下に指定された行にCannot read property 'setState' of nullを得ています。私は過去数時間の理由を理解しようとしてきましたが、それを理解できないようです。どんな助けでも大歓迎です。nullのプロパティ 'setState'を読み取ることができません - 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デザイン。 –

関連する問題