可以onChange = {this.nameHandler}调用nameHandler =(event)=> {}

时间:2019-05-10 11:14:43

标签: javascript reactjs ecmascript-6 arrow-functions eventhandler

下面是有效的代码段,

状态-

state = {
        name : '',
        age : ''
    }

onChangeHandler-

nameHandler = (event) =>{
        this.setState({name: event.target.value});
    }

UI-

<input type = "text" onChange = {this.nameHandler} value = {this.state.name}/>  

但是为什么以下操作不起作用?

状态-

state = {
        name : '',
        age : ''
    }

onChangeHandler-

nameHandler = (event) =>{
        this.setState({name: event.target.value});
    }

UI-

<input type = "text" onChange = {(event) =>this.nameHandler} value = {this.state.name}/>  

甚至没有以下内容,

state = {
        name : '',
        age : ''
    }

onChangeHandler-

nameHandler(event){
        this.setState({name: event.target.value})
    }

UI-

<input type = "text" onChange = {(event) =>this.nameHandler} value = {this.state.name}/>  

我了解我的问题的原因是缺乏箭头函数理论的知识。

请分享详细原因

3 个答案:

答案 0 :(得分:4)

考虑第二个示例

<input type = "text" onChange = {(event) =>this.nameHandler} value = {this.state.name}/> 

此处您未调用原始函数。这只是一个包装函数,它返回另一个函数。事件处理程序不受返回值的影响。

<input type = "text" onChange = {(event) =>this.nameHandler(event)} value = {this.state.name}/> 

答案 1 :(得分:1)

在下面对其进行更改以调用onChange函数:this.nameHandler-> this.nameHandler()

  <input type = "text" onChange = {(event) =>this.nameHandler(event)} value = {this.state.name}/>  

答案 2 :(得分:1)

您可以将event.target.value存储在这样的变量中

nameHandler = (event) =>{
    let {value=''} = event.target;
        this.setState({name: value});
}

  <input type = "text" onChange = {this.nameHandler} value = {this.state.name}/>