我对设置状态有疑问。
我在同一位置声明了2个handle方法。 1.work 2.打印输出但未设置状态。
处理程序在render方法中称为
如何在第二个处理程序中设置状态?
//handle definitions are on the same place
//this works
handleOpenOptions(){
this.setState({
showOptions: true,
menuOpened: false
});
}
//This print into console "test" but does not set showOptions: false
handleCloseOptions(){
console.log("test")
this.setState({
showOptions: false
})
}
//calling functions inside render method
<Collapse in={this.state.options}
timeout="auto"
unmountOnExit>
<List
component="div"
disablePadding>
<ListItem style={listStyle2} button>
<ListItemText
disableTypography
inset
primary={intl.get('MENUSERVERCONNECTION')} />
</ListItem>
<ListItem
style={listStyle2}
button
onClick={this.handleOpenOptions.bind(this)}>
<ListItemText
disableTypography
inset
primary={intl.get('MENUOPTIONS2')} />
<ReactModal className="modal"
isOpen={this.state.showOptions}
ariaHideApp={false}
contentLabel="Minimal Modal">
<MuiThemeProvider>
<div>
<AppBar title={intl.get('MODALOPTIONS')} />
<ul>
<li><p>American style date format</p></li>
</ul>
<Button className="modalClose" variant="contained" color="primary" onClick={this.handleCloseOptions.bind(this)}>{intl.get('BUTTCLOSEMODALEXTRAORDINARYEXPEDITION')} </Button>
</div>
</MuiThemeProvider>
</ReactModal>
</ListItem>
</List>
</Collapse>
答案 0 :(得分:0)
使用箭头功能
尝试将您的关闭处理程序更改为:
handleCloseOptions = () => {
console.log("test")
this.setState({
showOptions: false
})
}
答案 1 :(得分:0)
当您单击Button
时,也会同时单击ListItem
,因此调用handleCloseOptions
然后调用handleOpenOptions
。 (see here for more information)
为防止这种情况,您的handleCloseOptions
应该为:
handleCloseOptions(event) {
event.stopPropagation();
console.log("test")
this.setState({
showOptions: false
})
}