简体   繁体   English

为什么我不能在JSX中以这种方式使用三元运算符和箭头函数?

[英]Why can't I use a ternary operator and arrow function in this way in JSX?

With babel-preset-react (EDIT: babel version: v6.26.0 ), the following expression fails with the error " Invalid left-hand side in arrow function parameters " ( try on babel repl ): 使用babel-preset-react (编辑:babel版本: v6.26.0 )时,以下表达式失败并显示错误“ Invalid left-hand side in arrow function parameters ”( 尝试使用babel repl ):

true ? ("test") : x => 42      //FAILS, but only with `babel-preset-react`

Yet it works given a small modification: 然而,它有一个很小的修改:

true ? "test" : x => 42        //works fine

Both of these scenarios work as expected in seemingly any other configuration. 这两种情况在看似任何其他配置中都可以正常工作。

Is this a bug? 这是一个错误吗? Or is there something as a part of JSX parsing that causes this to happen? 或者有什么东西作为JSX解析的一部分导致这种情况发生?

Arrow functions are parsed differently than regular ones see Parsing order 箭头函数的解析方式与常规函数不同,请参阅解析顺序

Although the arrow in an arrow function is not an operator, arrow functions have special parsing rules that interact differently with operator precedence compared to regular functions. 虽然箭头函数中的箭头不是运算符,但箭头函数具有特殊的解析规则,与常规函数相比,它们与运算符优先级的交互方式不同。

let callback;

callback = callback || function() {}; // ok

callback = callback || () => {};      
// SyntaxError: invalid arrow-function arguments

callback = callback || (() => {});    // ok

It must have something to do with associativity of ternary operator (right-to-left) see link 它必须与三元运算符(从右到左)的关联性有关

The simple reason for this is that anything within () is treated as an condition to evaluate and hence it tries to find matching expressions after it which you aren't providing and hence it fails. 这样做的简单原因是()中的任何内容都被视为要评估的condition ,因此它会尝试在它未提供之后找到匹配的表达式,因此它会失败。 As a matter of fact 事实上

true ? ("test")? 1: 2 : x => 42

compiles just fine into 编译得很好

"use strict";

true ? "test" ? 1 : 2 : function (x) {
  return 42;
};

Check this demo 查看此演示

This is a bug. 这是一个错误。 I've created an issue on the babel github page: babel/babel#7234 . 我在babel github页面上创建了一个问题: babel / babel#7234 It is fixed in Babel 7. 它在Babel 7中修复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM