在箭头函数中使用和不使用大括号时,它的工作方式不同

问题描述 投票:0回答:4

这是另一个极客。我现在正在学习reactjs。当我尝试为我的应用程序创建一个

Button
元素时,我在代码中发现了这一点。我的想法是根据一个叫做
prop
type
来决定背景颜色。这类似于开关盒。请仔细检查代码以查找问题。

const colors = {
  primary: "#0d6efd",
  secondary: "#adb5bd",
  success: "#198754",
  info: "#0dcaf0",
  warning: "#ffc107",
  danger: "#dc3545",
  light: "#f8f9fa",
  dark: "#212529",
};

let bg = ((cl) => {
    colors[cl] || "#adb5bd";
})("primary");

let bg2 = ((cl) => colors[cl] || "#adb5bd")(type);

console.log(bg, bg2);

在控制台中,

undefined '#adb5bd'

我错过了什么吗?

javascript reactjs arrow-functions
4个回答
1
投票

您的函数没有返回任何内容。当您在编写函数时使用大括号表示法时,您需要显式返回。

let bg = ((cl) => {
    return colors[cl] || "#adb5bd";
})("primary");

1
投票

您不会退回任何东西。您可以使用

let bg = ((cl) =>  colors[cl] || "#adb5d")("primary");


0
投票

我相信最简单的方法是:

const Button = (props) => {
  const { type = 'primary' } = props; // we get the type with destructuring
  const colors = {
    primary: "#0d6efd",
    secondary: "#adb5bd",
    success: "#198754",
    info: "#0dcaf0",
    warning: "#ffc107",
    danger: "#dc3545",
    light: "#f8f9fa",
    dark: "#212529",
  };
  const color = colors[type];
  return <button style={{backgroundColor: color}}>I am the button with random color</button>
}

0
投票

这个行为太明显了。当我们使用花括号时,它不会隐式返回任何内容。但如果不使用大括号,它会返回表达式。

const colors = {
  primary: "#0d6efd",
  secondary: "#adb5bd",
  success: "#198754",
  info: "#0dcaf0",
  warning: "#ffc107",
  danger: "#dc3545",
  light: "#f8f9fa",
  dark: "#212529",
};

let bg = ((cl) => {
    colors[cl] || "#adb5bd"; <-------🔴
})("primary");

let bg2 = ((cl) => colors[cl] || "#adb5bd")("primary");

console.log(bg, bg2);

指出的行用作表达式,当明确写入时它将返回一些内容。

let bg = ((cl) => {
    return colors[cl] || "#adb5bd"; //returns "#0d6efd"
})("primary");

MDN 上阅读这篇文章。

© www.soinside.com 2019 - 2024. All rights reserved.