React添加点击事件、改变this指向

  • 方法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
  • 方法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
  • 方法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
发布了24 篇原创文章 · 获赞 4 · 访问量 4456

猜你喜欢

转载自blog.csdn.net/Amo__/article/details/101553512