mo49
4/4/2020 - 11:05 PM

00_ReactBindThis.md

Reactでthisのバインドの方法

コンストラクター内でbindする方法に統一するのがおすすめ

import React, {Component} from 'react'

// これがおすすめ
export default class MyEvent extends Component {
    constructor(props){
        super(props)
        this.show = this.show.bind(this)
    }
    show(e){
        console.log(`${this.props.greet}, ${e.target.value}`)
    }
    render(){
        return(
            <form>
                <label htmlFor="txtName">名前:</label>
                <input id="txtName" type="text" onChange={this.show} />
            </form>
        )
    }
}
import React, {Component} from 'react'

// 将来的には有望
export default class MyEvent extends Component {
    show = (e) => {
        console.log(`${this.props.greet}, ${e.target.value}`)
    }
    render(){
        return(
            <form>
                <label htmlFor="txtName">名前:</label>
                <input id="txtName" type="text" onChange={this.show} />
            </form>
        )
    }
}