【问题标题】:Arrow function is undefined when passed as props作为道具传递时箭头函数未定义
【发布时间】: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 = () =&gt; {}getColor() {},尝试将getColor 改为使用getColor = () =&gt; {}
  • 您在定义之前访问 getTaste。道具订单事项

标签: javascript reactjs react-props


【解决方案1】:

非箭头函数仍然在类中提升。如果在定义箭头函数后移动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

【讨论】:

    【解决方案2】:

    这是因为您对 getTastechangeColor 的定义不同:

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

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-26
      • 1970-01-01
      • 2018-08-04
      • 2016-09-08
      • 2015-01-25
      相关资源
      最近更新 更多