Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

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,什么时候正常打印?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
 <h2 onClick={this.handleClick.bind(this)}>React</h2>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...