首页 > 解决方案 > 作为道具传递时箭头函数未定义

问题描述

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

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); // {味道:未定义,颜色:ƒ}

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

标签: javascriptreactjsreact-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

推荐阅读