Reactjs React实用程序函数绑定此关键字
我有一个实用函数,但是Reactjs React实用程序函数绑定此关键字,reactjs,this,es6-modules,Reactjs,This,Es6 Modules,我有一个实用函数,但是这个是未定义的,即使我将它绑定到我的react组件中: /util/index: export const handleKeyPress = e =>{ console.log(this) } /component/input/: import {handleKeyPress} from "../util/index" class Input extends Component { constructor(props) { super(props)
这个是未定义的,即使我将它绑定到我的react组件中:
/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} />
}
}
从“./util/index”导入{handleKeyPress}
类输入扩展组件{
建造师(道具){
超级(道具)
此.state={
伊索彭:错
}
}
this.handleKeyPress=handleKeyPress.bind(this)
render(){
返回
}
}
因此,在我的输入键上,这个
在函数中是未定义的,即使我将它绑定到构造函数中。我能做什么?如果不想在构造函数中编写绑定,可以使用arrow函数编写事件
render()
return <input onKeyPress = {() =>
this.handleOnKeyPress() }/>
}
render()
返回
this.handleOnKeyPress()}/>
}
之后,您可以删除组件的绑定代码行。如果不想在构造函数中编写绑定,可以使用arrow函数编写事件
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)} />
}
}
render()
返回
this.handleOnKeyPress()}/>
}
之后,您可以删除组件的绑定代码行。从“./util/index”导入{handleKeyPress}
import { handleKeyPress } from "../util/index"
class Input extends Component {
constructor(props) {
super(props)
this.state = {
isOpen: false
}
}
render() {
return <input onKeyPress={(e) => handleKeyPress(e)} />
}
}
类输入扩展组件{
建造师(道具){
超级(道具)
此.state={
伊索彭:错
}
}
render(){
返回手柄按键(e)}/>
}
}
从调用函数中删除它,并从“./util/index”中删除绑定函数行import{handleKeyPress}
类输入扩展组件{
建造师(道具){
超级(道具)
此.state={
伊索彭:错
}
}
render(){
返回手柄按键(e)}/>
}
}
从调用函数中删除它并删除绑定函数行想知道为什么在util函数中需要这个
,这样我就可以在其他类似的组件中重用它export const handleKeyPress=e=>{console.log(this)}///bythis
你是说输入
类吗?是的,假设我想用util函数更改状态isOpen
,但是util函数无法识别this.state
。想知道为什么在util函数中需要this
,这样我就可以在其他类似组件中重用它了导入const handleKeyPress=e=>{console.log(this)}///这里所说的this
是指输入
类吗?是的,假设我想用util函数更改状态isOpen
,但是util函数无法识别这个状态。