繁体   English   中英

当作为 props 传递时,箭头函数未定义

[英]Arrow function is undefined when passed as props

当事件处理函数作为道具发送到子组件时。 正在接收正常功能,但不是胖箭头功能。

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

这是因为你定义getTastechangeColor不同:

  • getTaste被定义为引用箭头函数的属性
  • changeColor被定义为类上的函数

函数存在于类的原型中,属性存在于实例中。

因此,当在类的实例上初始化bananaEvents属性时,属性getTaste尚不存在,因此getTaste this.getTaste === undefined

getTaste定义为函数而不是属性:

bananaEvents = {
  color: this.changeColor,
  taste: this.getTaste
};
getTaste() {
  console.log("sweet");
};
changeColor() {
  console.log("Yellow");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM