search

Home  >  Q&A  >  body text

javascript - Why is this in React event null?

Why is this null?

class App extends Component {


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

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

        );
    }
}

export default App;

How to explain the following situation?

<!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>

So when will undefined be printed, when will null be printed, and when will it be printed normally?

習慣沉默習慣沉默2858 days ago530

reply all(1)I'll reply

  • PHPz

    PHPz2017-05-19 10:33:29

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

    reply
    0
  • Cancelreply