尝试触发状态更改功能时出错

时间:2015-08-24 09:54:16

标签: javascript css reactjs

我正在尝试为模态编写反应组件并获取错误:当调用openModal()时,“Uncaught TypeError:this.setState不是函数”。以下是我的代码:

class Header {

  constructor() {
      this.state = { showModal: false };
  } 

  openModal() {
      this.setState({showModal: true});
  }

  closeModal() {
      this.setState({showModal: false});
  }

  render() {
    return (
      <div className="Header">
        <ModalDialog heading="heading" show={this.state.showModal}>
          <p>Body</p>
        </ModalDialog>
        <div className="Header-container">
          <Navigation className="Header-nav" />
          <div className="Navigation2">

            <Button bsStyle='primary' onClick={this.openModal.bind(this)}>Sign in</Button>

            <Button bsStyle='info' href="/register" onClick={Link.handleClick}>Sign up</Button>

          </div>
        </div>
      </div>
    );
  }

}

class ModalDialog {

  render() {
    if (this.props.show) {
        return (
        <div className="Overlay">
          <Modal heading={this.props.heading}>
            <div>{this.props.children}</div>
          </Modal>
        </div>
      );
    }
    return null;
  }
};

class Modal {

  render() {
    return (
      <div className="Modal effect">
        <h3>{this.props.heading}</h3>
        <div className="content">
          {this.props.children}
        </div>
      </div>
    );
  }
};

我也试图将一个className传入Header组件的元素<div className="Modal effect">来改变Modal的尺寸,这可能吗?

如果有人可以帮我解决这个问题会很棒。我刚刚开始使用React。感谢

2 个答案:

答案 0 :(得分:2)

我也试图将一个className传递给Header组件中的元素以更改Modal的尺寸,这可能吗?

这通常是为什么制作道具,传递这样大小的静态信息。 所以简单地将你的class / size / staticprops作为这样的道具传递:

<ModalDialog size={//whatever you need} className="Modal effect"/> 

从ModalDialog传递给Modal

<Modal size={this.props.size} />

然后你必须在你的Modal中使用它,无论你想要什么目的。有关道具的更多信息:https://facebook.github.io/react/docs/transferring-props.html

希望有所帮助

答案 1 :(得分:0)

我对reactJS并不熟悉,但这对我来说不合适:

constructor() {
      this.state = { showModal: false };
}

应该是:

constructor() {
      this.setState = ({ showModal: false });
}

否则,您的Header类将其state属性设置为{ showModal: false }

显然没有'setState'成员函数。