首页 > 解决方案 > ReactJs 事件绑定

问题描述

import React, { Component } from 'react';

class SayHello extends React.Component {
    constructor(props) {
        super(props);
        this.state = { message: 'Hello!' };
        // This line is important!
        this.handleClick = this.handleClick.bind(this);
    }

    handleClick() {
        console.log(this.state.message);
    }

    render() {
        return <button onClick={this.handleClick}>Say hello</button>;
    }
}

export default SayHello;`

为什么我们需要绑定?我理解上下文,但不会this引用实例,有人可以用非反应方式或简单的 JS 类的例子来解释。

标签: javascriptreactjs

解决方案


推荐阅读