无法读取 null 的属性“setState" - React.js、Modal、Bootstrap [英] Cannot read property 'setState' of null - React.js, Modal, Bootstrap

查看:112
本文介绍了无法读取 null 的属性“setState" - React.js、Modal、Bootstrap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying React.js for the first time in trying to build this web app. I am getting Cannot read property 'setState' of null on the specified line below. I've been trying to figure out why for the past few hours and cannot seem to figure it out. Any help would be greatly appreciated.

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

推荐答案

constructor() 内绑定你的组件类方法(在构造器内绑定比在 render() 为了性能):

bind your component class methods inside the constructor() (binding inside constructor is better than binding inside render() for performance sake):

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

这篇关于无法读取 null 的属性“setState" - React.js、Modal、Bootstrap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆