一条线箭头不带大括号的功能-不能使用分号? [英] One line arrow functions without braces - can't have a semicolon?

查看:68
本文介绍了一条线箭头不带大括号的功能-不能使用分号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是React和ES6语法的新手,我发现有趣的是,如果我写:

I'm new to React and ES6 syntax, and something I found interesting was that if I write:

return <input onChange={event => console.log(event.target.value);} />;

这将不起作用.我收到找不到模块"错误.

This will not work. I get a "Cannot find module" error.

但是,如果我在箭头函数中删除了分号:

But if I remove the semicolon in the arrow function:

return <input onChange={event => console.log(event.target.value)} />;

效果很好.如果我保留分号但加了大括号,则这样:

It works just fine. And if I kept the semicolon but added braces, as so:

return <input onChange={event => { console.log(event.target.value); }} />;

这也可以.上面第一个示例不起作用的原因是什么?

This works too. What is the reason for the first example above not working?

推荐答案

要正确理解为什么会发生这种情况,请确保我们知道 expression 块之间的区别.

To properly understand why this is the case, let's make sure we know the difference between an expression, and a block.

在最基本的层次上, expression 是一些代表某种值的代码.所以123a + b + ccalculateSomething()都是表达式.表达式中不包含分号.

At the most basic level, an expression is a bit of code that represents a value of some sort. So 123, a + b + c, calculateSomething(), these are all expressions. Expressions don't include semicolons in them.

一个 block 是语句列表.这些语句用花括号{ }包围,并用分号分隔.

A block in JS is a list of statements. These statements are surrounded by curly braces { }, and separated by semicolons.

通常,语句由一个表达式和一个分号组成.所以,

Quite often, statements consist of an expression followed by a semicolon. So,

a = b + c;

是一个声明.还有其他类型的语句:letvarforwhilereturn

is a statement. There are other kinds of statements: let, var, for, while, return, etc.

现在,返回箭头功能.箭头功能可以有两种形式:

Now, back to the arrow function. An arrow function can come in two forms:

(some, args) => <an expression>
(some, args) => { <a statement>; <a statement>; ... }

请注意,第一种形式采用表达式,即单一形式.如果您使用的是 block ,则应该只有分号,例如第二种形式.

Note the first form takes an expression, a single one. There should only be semicolons if you're using a block, like in the second form.

JSX的工作方式如下:

JSX works like this:

<input onChange={ <an expression> } />

您将所需道具的名称加上等号,然后在括号中添加一个表达式.请记住,单个表达式没有分号.

You put the name of the prop you want, an equal sign, then a single expression in braces. Remember, single expressions don't have semicolons.

箭头功能是一个表达式.所以,如果您要在此处放置分号...

An arrow function is an expression. So, if you were to put a semicolon here...

<input onChange={ () => 'hello' ; } />

JS将看到该表达式,然后在其后看到分号并崩溃,因为它不应该在那里.

JS will see the expression, then see the semicolon after it and crash, because it's not supposed to be there.

这篇关于一条线箭头不带大括号的功能-不能使用分号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆