Не удается прочитать свойство 'setState' из null - React.js, Modal, Bootstrap

Я впервые пытаюсь создать React.js, пытаясь создать это веб-приложение. я получаю 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 ответ

Решение

Привязать ваши методы класса компонента внутри constructor() (привязка внутри конструктора лучше, чем привязка внутри render() ради производительности):

constructor(props) {
    super(props);
    this.state = {show: false};
    this.showModal = this.showModal.bind(this);
    this.hideModal = this.hideModal.bind(this);
}
Другие вопросы по тегам