搜索

首页  >  问答  >  正文

javascript - React事件中的 this为什么是null?

为什么this为null?

class App extends Component {


    handleClick(e) {
        console.log(this)//为什么是 null?
    }

    render() {
        return (
         
            <h2 onClick={this.handleClick}>React</h2>

        );
    }
}

export default App;

下面这种情况如何解释?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<button onclick="func()">click</button> // 打印 undefined
<button onclick="app.handleClick()">click</button> // 打印 App
<script>

    class App {
        handleClick() {
            console.log(this)
        }
    }
    const app = new App
    const func = app.handleClick
</script>
</body>
</html>

所以什么时候会打印undefined,什么时候会打印null,什么时候正常打印?

習慣沉默習慣沉默2857 天前528

全部回复(1)我来回复

  • PHPz

    PHPz2017-05-19 10:33:29

    雷雷

    回复
    0
  • 取消回复