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

Arrow function is undefined when passed as props

当事件处理函数作为 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("props from FruitClass", 道具); // {口味:未定义,颜色:ƒ}

为什么箭头函数在子组件中没有作为函数接收?当像这样作为 props 发送时,如何接收箭头函数作为子函数的适当函数?

非箭头函数仍然在 classes 中提升。如果您在定义箭头函数后移动 bananaEvents,您的 class 将正常工作。

我刚才用

测试了这个
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 定义为 class
  • 上的函数

函数存在于 class 的原型上,属性存在于实例上。

所以当 bananaEvents 属性 在 class 的实例上初始化时, 属性 getTaste 还不存在,因此 this.getTaste === undefined.

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

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