无法更改处理程序内部的变量

时间:2018-07-13 08:58:12

标签: javascript reactjs

我对设置状态有疑问。

我在同一位置声明了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>

2 个答案:

答案 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
    })
}