javascript - 作为道具传递时箭头函数未定义
问题描述
当事件处理函数作为道具发送给子组件时。正在接收正常功能,但不是胖箭头功能。
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("来自 FruitClass 的道具", props); // {味道:未定义,颜色:ƒ}
为什么箭头函数没有作为子组件中的函数接收?当像这样作为道具发送时,如何在孩子中接收箭头功能作为适当的功能?
解决方案
非箭头函数仍然在类中提升。如果在定义箭头函数后移动bananaEvents,您的类将正常工作。
我刚刚测试了这个
class Test {
vars = { one: this.firstFunction(), two: this.secondFunction() }
firstFunction() { return 1
}
secondFunction = () => 2
}
const test1 = new Test(); // will give an error function undefined
和
class Test2 {
firstFunction() { return 1
}
secondFunction = () => 2
vars = { one: this.firstFunction(), two: this.secondFunction() }
}
const test2 = new Test2(); // works normally
推荐阅读
- node.js - Postgresql 查询超过 30 秒,在 Heroku 上失败
- xml - 基于 XML 的 Document 文件能否在 Web 浏览器中呈现
- django - Django auth 用户注册“用户”对象没有属性“配置文件”
- python - 尝试加载“menus.templatetags.menus_tags”时引发 ImportError:无法从“menus.models”导入名称“菜单”
- python-3.x - 与所有边等距的文本对齐(居中对齐)
- java - spring boot 无法读取安装在多个实例中的 minikube 主机路径中的类路径中提供的库
- audio - ffmpeg 导出的文件坏了
- python - 正则表达式在 python 程序中的 Windows 中不起作用
- kotlin - micronaut 中的 Rxhttpclient 代理配置
- c# - 如何在c#中获取多行字符串的未知行中的字符索引