[英]Arrow function is undefined when passed as props
when event handler functions are sent as props to child components.当事件处理函数作为道具发送到子组件时。 normal functions are being received, but not fat arrow functions.正在接收正常功能,但不是胖箭头功能。
import React, { Component } from "react";
export default class FruitClass extends Component {
bananaEvents = {
color: this.changeColor,
taste: this.getTaste
};
getTaste = () => {
console.log("sweet");
};
changeColor() {
console.log("Yellow");
}
render() {
return (
<div>
<Banana {...this.bananaEvents} />
</div>
);
}
}
function Banana(props) {
console.log("props from FruitClass", props); // {taste: undefined, color: ƒ}
return (
<div>
<button onClick={props.color}>click me</button>
</div>
);
}
console.log("props from FruitClass", props); console.log("来自 FruitClass 的道具", props); // {taste: undefined , color: ƒ} // {味道:未定义,颜色:ƒ}
why arrow function, is not received as a function in child component ?为什么箭头函数没有作为子组件中的函数接收? how to receive arrow functions as proper functions in child, when sent as props like this?当像这样作为道具发送时,如何将箭头函数作为子函数的正确函数接收?
Non-arrow functions are still hoisted in classes.非箭头函数仍然在类中提升。 If you move bananaEvents after defining the arrow functions your class will work normally.如果您在定义箭头函数后移动bananaEvents,您的类将正常工作。
I tested this just now with我刚刚测试了这个
class Test {
vars = { one: this.firstFunction(), two: this.secondFunction() }
firstFunction() { return 1
}
secondFunction = () => 2
}
const test1 = new Test(); // will give an error function undefined
and和
class Test2 {
firstFunction() { return 1
}
secondFunction = () => 2
vars = { one: this.firstFunction(), two: this.secondFunction() }
}
const test2 = new Test2(); // works normally
It is because you are defining getTaste
and changeColor
differently:这是因为你定义getTaste
和changeColor
不同:
getTaste
is defined as a property referencing an arrow function getTaste
被定义为引用箭头函数的属性changeColor
is defined as function on the class changeColor
被定义为类上的函数Functions live on the prototype of the class, properties live on the instance.函数存在于类的原型中,属性存在于实例中。
So when the bananaEvents
property is initialised on an instance of the class, the property getTaste
does not exist yet, hence this.getTaste === undefined
.因此,当在类的实例上初始化bananaEvents
属性时,属性getTaste
尚不存在,因此getTaste
this.getTaste === undefined
。
Define getTaste
as a function instead of a property:将getTaste
定义为函数而不是属性:
bananaEvents = {
color: this.changeColor,
taste: this.getTaste
};
getTaste() {
console.log("sweet");
};
changeColor() {
console.log("Yellow");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.