无法读取 null 的属性“setState” - React.js、Modal、Bootstrap

IT技术 reactjs react-bootstrap
2021-05-10 20:31:14

我第一次尝试使用 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个回答

将您的组件类方法constructor()绑定在内部(render()出于性能考虑,在构造函数内部绑定比在内部绑定更好):

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