Javascript 无法更改处理程序内的变量
我对设置状态有问题 我在同一个地方声明了两个句柄方法。1.工作2。打印输出,但不设置状态 处理程序在render方法内部调用 如何在第二个处理程序中设置状态Javascript 无法更改处理程序内的变量,javascript,reactjs,Javascript,Reactjs,我对设置状态有问题 我在同一个地方声明了两个句柄方法。1.工作2。打印输出,但不设置状态 处理程序在render方法内部调用 如何在第二个处理程序中设置状态 //handle definitions are on the same place //this works handleOpenOptions(){ this.setState({ showOptions: true, menuOpened: false }); } //This prin
//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>
//句柄定义位于同一位置
//这很有效
手足畸形{
这是我的国家({
展示选项:正确,
menuOpened:错误
});
}
//这会打印到控制台“测试”,但不会设置showOptions:false
handleCloseOptions(){
控制台日志(“测试”)
这是我的国家({
showOptions:false
})
}
//在render方法内调用函数
- 美式日期格式
{intl.get('BUTTCLOSEMODALEXTRAORDINARYEXPEDITION')}
使用箭头功能
尝试将关闭处理程序更改为:
handleCloseOptions = () => {
console.log("test")
this.setState({
showOptions: false
})
}
当您点击
按钮时,您也会点击列表项
,因此handleCloseOptions
是调用,然后handleoptions
是调用。()
为防止出现这种情况,您的手柄关闭选项应为:
handleCloseOptions(event) {
event.stopPropagation();
console.log("test")
this.setState({
showOptions: false
})
}
你能试着整理一下你的代码缩进吗?它伤到我的眼睛了。不能设置状态。