我有一个实用函数,但是即使我将它绑定到我的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
,该函数也未定义。我该怎么办?
如果您不想在构造函数中编写绑定,则可以使用箭头函数编写事件。
render()
return <input onKeyPress = {() =>
this.handleOnKeyPress() }/>
}
之后,您可以删除组件的绑定代码行。
import { handleKeyPress } from "../util/index"
class Input extends Component {
constructor(props) {
super(props)
this.state = {
isOpen: false
}
}
render() {
return <input onKeyPress={(e) => handleKeyPress(e)} />
}
}
从调用函数中删除并删除绑定函数行