无法读取属性' setState' of null - React.js,Modal,Bootstrap

时间:2016-11-19 15:16:46

标签: reactjs react-bootstrap

我第一次尝试使用React.js来构建这个Web应用程序。我在下面的指定行上获得了Cannot read property 'setState' of null。我一直试图找出过去几个小时的原因,似乎无法弄明白。任何帮助将不胜感激。

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

1 个答案:

答案 0 :(得分:8)

绑定constructor()中的组件类方法(为了性能,绑定内部构造函数优于绑定在render()内部):

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