【发布时间】:2020-02-21 15:37:17
【问题描述】:
当事件处理函数作为道具发送给子组件时。正在接收正常功能,但不是胖箭头功能。
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); // {味道:未定义,颜色:ƒ}
为什么箭头函数在子组件中没有作为函数接收?当像这样作为道具发送时,如何在孩子中接收箭头函数作为适当的函数?
【问题讨论】:
-
我相信这是因为你
spreading 道具。去掉...,看看箭头函数是否通过 -
,给出语法错误“...预期”,我想发送两个事件处理程序,即 changeColor、getTaste -
因为它不是箭头函数!您已经定义了
getTaste = () => {}但getColor() {},尝试将getColor改为使用getColor = () => {} -
您在定义之前访问 getTaste。道具订单事项
标签: javascript reactjs react-props