React 元素和粗箭头函数 [英] React elements and fat arrow functions

查看:30
本文介绍了React 元素和粗箭头函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Redux 示例中,使用的语法是:

const App = () =>(<div><添加待办事项/><VisibleTodoList/><页脚/>

)

我正在玩一个新的示例应用程序,并用大括号而不是圆括号错误地输入了上面的代码,如下所示:

const App = () =>{<div><添加待办事项/><VisibleTodoList/><页脚/>

}

我控制台记录了以下两个结果,结果似乎相同.我的问题是这两个之间有什么区别,为什么 React 喜欢括号而不喜欢大括号?

解决方案

TL;DR

你的第一个例子或多或少相当于:

var App = function() { return 

...

;};

你的第二个或多或少相当于:

var App = function() { <div>...</div>;};

React 可能抱怨第二个示例中没有返回任何内容.

稍长的版本

让我们把 React 排除在外.在 es6 中你可以像这样创建一个胖箭头函数:

const getWord = () =>{返回独角兽";}

我们得到了一条捷径,可以用更少的代码做同样的事情:

const getWord = () =>'独角兽';

unicorn 即使您从未在任何地方明确键入 return 也会返回.

在您的第一个示例中,您将 JSX 括在括号中.我们简单示例中的等效项是:

const getWord = () =>('独角兽');

或者这个

const getWord = () =>('独角兽');

最后四个例子是等价的.希望有帮助!

In the Redux examples, the syntax used is:

const App = () => (
  <div>
    <AddTodo />
    <VisibleTodoList />
    <Footer />
  </div>
)

I was toying around with a new example app and mistyped the above code with curly brackets instead of parentheses like so:

const App = () => {
  <div>
    <AddTodo />
    <VisibleTodoList />
    <Footer />
  </div>
}

I console logged both of the following and the result seemed to be the same. My question is what is the difference between these 2 and why does React like the parentheses but not the curly brackets?

解决方案

TL;DR

Your first example is more or less equivalent to:

var App = function() { return <div>...</div>; };

Your second is more or less equivalent to:

var App = function() { <div>...</div>; };

React is probably complaining that nothing is being returned in the second example.

Slightly Longer Version

Let's take React out of the equation. In es6 you can create a fat arrow function like this:

const getWord = () => {
  return 'unicorn';
}

And we're given a shortcut to do the same thing with less code:

const getWord = () => 'unicorn';

unicorn is returned even though you don't ever explicitly type return anywhere.

In your first example, you wrapped your JSX in parenthesis. The equivalent in our simple example is:

const getWord = () => ('unicorn');

or this

const getWord = () => (
  'unicorn'
);

The last four examples are equivalent. Hope that helps!

这篇关于React 元素和粗箭头函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆