React add a click event, change this point

  • method 1
import React, { Component } from 'react'

class ClickComponent extends Component {
    constructor(props){
        super(props)
        this.state ={
            msg: '这是一个标题'
        }
    }
    run() {
        alert(this.state.msg)
    }
    render() {
        return (
        <div>
            <button onClick={this.run.bind(this)}>请点击</button>
        </div>
        )
    }
}

export default ClickComponent
  • Method 2
import React, { Component } from 'react'
class ClickComponent extends Component {
    constructor(props){
        super(props)
        this.state ={
            msg: '这是一个标题23'
        }
        this.getClick = this.getClick.bind(this);
    }
    getClick() {
        alert(this.state.msg)
    }
    render() {
        return (
        <div>
            <button onClick={this.getClick}>请点击</button>
        </div>
        )
    }
}

export default ClickComponent
  • Method 3
import React, { Component } from 'react'
class ClickComponent extends Component {
    constructor(props){
        super(props)
        this.state ={
            msg: '这是一个标题233'
        }
    }
    getClick=()=>{
        alert(this.state.msg)
    }
    render() {
        return (
        <div>
            <button onClick={this.getClick}>请点击</button>

        </div>
        )
    }
}

export default ClickComponent
Published 24 original articles · won praise 4 · Views 4456

Guess you like

Origin blog.csdn.net/Amo__/article/details/101553512