我正在使用setState来切换弹出窗口的视图(来自reactstrap的模式为ReactJS的引导程序库)。当我运行组件时,弹出窗口按预期显示,如果我关闭它,它将按预期消失。如果再次调用该组件,它将不会更新状态,因此它不会再次呈现de popup。只有我再次刷新页面。
三个弹出子组件之一:
export class MatchPopup extends React.Component {
constructor(props) {
super(props);
this.state = {
modal: false,
};
this.toggle = this.toggle.bind(this);
}
componentDidMount(){
this.toggle()
}
toggle() {
this.setState({
modal: !this.state.modal
});
console.log(this.state.modal)
}
render() {
<Modal isOpen={this.state.modal} toggle={this.toggle}>
</Modal>
}
}
在我的父组件中,这是渲染弹出组件的函数。
export class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
match: this.props.match,
token: this.props.token,
popup: '',
statusIcon: ''
};
}
matched(){
this.setState({popup: <MatchPopup showAlert={this.props.showAlert} match={this.props.match} token={this.props.token}/>})
}
challenged(){
this.setState({popup: <ChallengedPopup showAlert={this.props.showAlert} match={this.props.match} token={this.props.token}/>})
}
accepted(){
this.setState({popup: <AcceptedPopup showAlert={this.props.showAlert} match={this.props.match} photo_url_hd={this.props.photo_url_hd} token={this.props.token}/>})
}
componentDidMount(){
// pop up to challenge someone this is the child component that i mentioned
if(this.props.match.challenged == 0){
this.setState({statusIcon:<div tabIndex="1" className="challengeButton" onClick={() => this.matched()}><div className="Paperplane"><FaPaperPlane /></div></div>})
}
// pop up if someone challenges you
if(this.props.match.challenged != 0 && this.props.match.challenged != 3 && this.props.match.userBeingChallenged == 1 ){
this.setState({statusIcon: <div tabIndex="1" className="challengeButton" onClick={() => this.challenged()}><div className="Envelope"><FaEnvelope /></div></div>})
}
//you have challenged someone
if(this.props.match.challenged != 0 && this.props.match.challenged != 3 && this.props.match.userBeingChallenged == 0){
this.setState({statusIcon:<div tabIndex="1" className="challengeButtonDisabled"><div className="paperplaneDisabled"><FaPaperPlane /></div></div>})
}
//match is accepted
if(this.props.match.challenged == 3){
this.setState({statusIcon:<div tabIndex="1" className="challengeButton" onClick={() => this.accepted()}><div className="Rocket"><FaRocket /></div></div>})
}
}
render()
{
var popup = this.state.popup
return (
<div className="...">
<div className="..."><img className="friendPic" src={this.props.match.friend.photo_url}/>{this.state.statusIcon}{popup}</div>
<p className="...">{this.props.match.friend.name}</p>
</div>
)
}
答案 0 :(得分:0)
根据当前状态设置状态时,应使用setState
toggle() {
this.setState(state => ({
modal: !state.modal
}));
}