函数签名的Javascript语法



在来自MUI的style的文档中,我遇到了这个函数签名:

styled(Component, [options])(styles) => Component

我在MUI演示中发现了许多使用这种语法的例子。

我觉得我缺乏基本的语法知识,因为我没有掌握(styles) => Component部分。我知道这是一个lambda表达式,但对我来说,它不是函数签名的一部分,因为它没有包含在括号中。

有人能解释一下它的作用以及为什么它与这样的签名不同吗

styled(Component, [options], (styles) => Component)

styled(Component, [options])(styles) => Component

如果您不熟悉文档中该部分使用的语法,那么说明后的示例非常好。

styled是一个接受两个参数(Component和可选的options(的函数。

它返回一个函数。

返回的函数接受一个参数(styles(并返回一个Component


相比之下,您的版本:

styled(Component, [options], (styles) => Component)

这里,styled是一个有三个参数的函数。

  • Component
  • options(标记为可选,但不能,因为第三个参数未标记为可选(
  • 接受一个参数(styles(并返回一个Component的函数

缺少styled的返回值。

这是API描述语法,而不是实际的JS代码,其中'=>'用于描述从函数返回的值类型(在本例中为Component类型的对象(。这有点令人困惑,因为它看起来像一个常规的JS箭头函数。然而,箭头之前的语法是有效的JS代码,并描述了一个自调用函数。styled返回一个函数,该函数可以通过在函数调用中添加括号来立即调用。

// example implementation of styled
const styled = function(component, options = {}) {
return function(styles) {return new Component(styles)};
}
// long version of API description
const returnedFunction = styled(myComponent, options);
const returnedComponent = returnedFunction(styles);
// condensed version
const returnedComponent = styled(MyComponent)(styles);

您提供的示例不起作用,因为您的箭头函数将在实际函数调用之前执行,并且只有其返回值(在您的情况下为Component(将作为第三个参数传递,所以回调函数本身的styles参数不会产生影响。

最新更新