反应中使用箭头功能无法通过此功能?

时间:2017-04-28 05:18:33

标签: javascript

我使用箭头功能

传递 e 的未定义值
<input type="checkbox" onChange={e=> this.handleCheck(this, 123)} />

handleCheck = (e, number) => {
console.log(number) //123
console.log(e.target.checked) //undefined
console.log(e.target) //undefined
}

怎么了?

1 个答案:

答案 0 :(得分:0)

在您的代码中,e.target将是未定义的。这是因为您将此作为参数传递,React引用 <input type="checkbox" onChange={e=> this.handleCheck(e, 123)}/> Here `e` is value not event. console.log(e) will print true on checked and false on unchecked. class`。

案例1.

 <input type="checkbox" onChange={this.handleCheck.bind(this)}/>//this is event here

    handleCheck(e)
    {
     console.log(e.target.value)// Here you will get value
    }

案例2:

 <input type="checkbox" value="me" onChange={this.handleCheck.bind(this,123)}/>//this is event here

    handleCheck(value,e)// if you bind method to this and pass extra arguments than you will get it in reverse order
    {
console.log(value)//123
     console.log(e.target.value)// me
    }

案例3:

{{1}}