最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - One line arrow functions without braces - can't have a semicolon? - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question asked May 24, 2018 at 4:36 rb612rb612 5,6033 gold badges35 silver badges80 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

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

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.

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;

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 e in two forms:

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

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 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 will see the expression, then see the semicolon after it and crash, because it's not supposed to be there.

发布评论

评论列表(0)

  1. 暂无评论