绑定此关键字的实用工具功能

问题描述 投票:0回答:2

我有一个实用函数,但是即使我将它绑定到我的react组件中,this也是未定义的:

/util/index:

export const handleKeyPress = e =>{
  console.log(this)
}

/component/input/:

import {handleKeyPress}  from "../util/index"
class Input extends Component {
  constructor(props) {
    super(props)
    this.state = {
        isOpen: false
    }
  }
  this.handleKeyPress = handleKeyPress.bind(this)

  render(){
   return <input onKeyPress = {this.handleKeyPress} />
 }
}

因此,在我的输入按键上,即使我在构造函数中绑定了this,该函数也未定义。我该怎么办?

reactjs this es6-modules
2个回答
0
投票

如果您不想在构造函数中编写绑定,则可以使用箭头函数编写事件。

render()
return <input onKeyPress = {() => 
this.handleOnKeyPress() }/>
 } 

之后,您可以删除组件的绑定代码行。


0
投票
    import { handleKeyPress } from "../util/index"
    class Input extends Component {
      constructor(props) {
        super(props)
        this.state = {
          isOpen: false
        }
      }

      render() {
        return <input onKeyPress={(e) => handleKeyPress(e)} />
      }
    }

从调用函数中删除并删除绑定函数行

© www.soinside.com 2019 - 2024. All rights reserved.