Javascript 尝试触发函数进行状态更改时出错
我试图为一个模态编写一个react组件,并在调用openModal()时得到错误:“UncaughtTypeError:this.setState不是函数”。下面是我的代码:Javascript 尝试触发函数进行状态更改时出错,javascript,css,reactjs,Javascript,Css,Reactjs,我试图为一个模态编写一个react组件,并在调用openModal()时得到错误:“UncaughtTypeError:this.setState不是函数”。下面是我的代码: class Header { constructor() { this.state = { showModal: false }; } openModal() { this.setState({showModal: true}); } closeModal() {
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>
);
}
};
类标题{
构造函数(){
this.state={showmodel:false};
}
openModal(){
this.setState({showmodel:true});
}
closeModal(){
this.setState({showmodel:false});
}
render(){
返回(
身体
登录
注册
);
}
}
类模态对话{
render(){
如果(这个.道具.表演){
返回(
{this.props.children}
);
}
返回null;
}
};
类模态{
render(){
返回(
{this.props.heading}
{this.props.children}
);
}
};
我还试图将类名从Header组件传递到元素
,以更改模态的维度,这可能吗
如果有人能帮我解决这件事就太好了。我刚从React开始。谢谢我还试图将类名从Header组件传递到元素中,以更改模态的维度,这可能吗
这通常是道具的用途,传递静态信息,例如大小。
因此,只需将类/大小/静态道具作为道具传递,如下所示:
<ModalDialog size={//whatever you need} className="Modal effect"/>
从ModalDialog传递给Modal
<Modal size={this.props.size} />
然后你只需要在你的模态中使用它,无论你想要什么。有关道具的更多信息:
希望对您有所帮助我不熟悉reactJS,但这在我看来是错误的:
constructor() {
this.state = { showModal: false };
}
如果是:
constructor() {
this.setState = ({ showModal: false });
}
?
否则,头类将其state属性设置为{showmodel:false}
它显然没有“setState”成员函数。我设法修复了它,不得不在代码上方添加super()。但是关于将类传递到组件中。有解决办法吗?谢谢