我有一个Newsletter组件,要在页面加载为弹出窗口时显示。现在,单击按钮后会显示它,该怎么办?我知道有react-popup,但我不想那样做,这是我的组件:
import React from 'react';
import './newsletter.css';
class Newsletter extends React.Component {
constructor(props) {
super(props);
this.state = {
modalOpened: false
};
this.modalToggle = this.modalToggle.bind(this);
}
modalToggle() {
this.setState({ modalOpened: !this.state.modalOpened });
}
render() {
const coverClass = this.state.modalOpened ? 'modal-cover modal-cover-active' : 'modal-cover';
const containerClass = this.state.modalOpened ? 'modal-container modal-container-active' : 'modal-container';
return (
<div>
<button className="btn btn-primary" onClick={this.modalToggle}>
Sign up for our Newsletter!
</button>
<div className={containerClass}>
<div className="modal-header" />
<h1> Want more offers? Sign Up! </h1>
<div className="modal-body">
<form action="#" className="form">
<input type="email" className="input" />
<input className="newsletter-submit" type="submit" value="Submit" />
</form>
</div>
<div className="modal-footer" />
</div>
<div className={coverClass} onClick={this.modalToggle} />
</div>
);
}
}
export default Newsletter;
我尝试将其放入ComponentWillMount周期中,但没有成功,我该怎么办?
答案 0 :(得分:0)
如果您希望模态在创建组件时直接显示,则可以将modalOpened
设置为true
而不是构造函数中的false
。
constructor(props) {
super(props);
this.state = {
modalOpened: true
};
this.modalToggle = this.modalToggle.bind(this);
}
如果要在一定时间后显示模式,可以使用setTimeout
,该setState
在经过一定时间后才使用componentDidMount() {
setTimeout(() => this.setState({ modalOpened: true }), 3000);
}
。
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference