React.JS - 在`onClick`事件上调用函数会导致`this`在函数中未定义

问题描述 投票:1回答:1

我有以下React.JS(Next.JS)代码:

export default class NavBar extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            menuOpen: false
        };
    }

    render() {
        return <img id="menu-button" src="/static/menu.svg" onClick={this.toggleMenu}></img>;
    }

    toggleMenu() {
        this.setState({ menuOpen: this.state.menuOpen ? false : true });
    }

};

但是,当单击图像并调用toggleMenu时,我收到一条错误消息,指出this未定义。这是有道理的,因为函数被放入onClick事件,但我该如何解决这个问题呢?

node.js reactjs this
1个回答
3
投票

您需要将this上下文显式绑定到您的函数,如:

this.toggleMenu.bind(this)

或者使用箭头符号重新定义你的toggleMenu函数,它隐含地这样做:

toggleMenu = () => {
  // method body here...
}
© www.soinside.com 2019 - 2024. All rights reserved.