react 条件渲染

为什么我们不能使用If-Else以及三元运算符如何提供帮助 (Why We Can’t Use If-Else and How the Ternary Operator can Help)

One of the great strengths of the React.js framework is its modular design philosophy. When we break our page into modular components, we also gain a lot of control over how, where, when, and whether a component is rendered. The latter question, the “whether,” seems especially important in an interactive web app. Without it, we wouldn’t have things like modals, dropdown lists, and accordion menus. These are all examples of conditional rendering.

React.js框架的一大优势是其模块化的设计理念。 当我们将页面分为模块化组件时,我们还获得了如何呈现组件,如何呈现,何时呈现以及是否呈现组件的大量控制权。 在交互式Web应用程序中,后一个问题“是否”显得尤为重要。 没有它,我们将不会有模态,下拉列表和手风琴菜单之类的东西。 这些都是条件渲染的示例。

The word “conditional” might tip us off here that we’re going to be dealing with, well, conditionals (i.e., if, else if, else). If some condition is met, render one component, else (if the condition isn’t met), render another one. While, logically, this is true, syntactically, it won’t be so simple. Here’s an example:

“有条件的”一词可能会在这里提示我们,我们将要处理有条件的(即,如果,否则,如果不是)。 如果满足某些条件,则渲染一个组件,否则(如果不满足条件),则渲染另一个组件。 虽然从逻辑上讲这是正确的,但从语法上讲,这并不是那么简单。 这是一个例子:

Here we have a template to create a flashcard for studying. We want to start with a term, and render the definition after we click on the card. The FlashCard component also has a state of “clicked” initialized to false. This state is how we can keep track of our clicks.

这里我们有一个模板来创建学习卡片。 我们想从一个词开始,然后在单击卡片后渲染定义。 FlashCard组件还具有初始化为false的“单击”状态。 在这种状态下,我们可以跟踪点击次数。

NOTE: In a full-size React app, you might choose to keep track of your clicks via object mutation (i.e., adding a “clicked” key to the object when storing it in state in a parent component), or via props from a parent component. I’m using state in this example to limit our scope to a single component/file.

注意:在全尺寸的React应用中,您可以选择通过对象突变(例如,将对象存储在父组件中的状态时向对象添加“被单击”键)或通过来自道具的道具来跟踪点击。父组件。 在此示例中,我使用状态将范围限制为单个组件/文件。

React uses JSX, which allows us to write our code using HTML-like syntax, making it easy to visualize how it will render. The above code looks like we’re using an HTML div tag. JSX gives us that HTML feel, while also allowing us to implement JavaScript inside those curly braces. This is presumably where our conditional logic would belong. So, what if we just use a standard conditional statement, like so:

React使用JSX,这使我们能够使用类似HTML的语法编写代码,从而使可视化呈现方式变得容易。 上面的代码看起来像我们正在使用HTML div标签。 JSX给我们带来HTML的感觉,同时也使我们能够在这些花括号内实现JavaScript。 这大概是我们的条件逻辑所属的地方。 因此,如果我们仅使用标准条件语句,如下所示:

The weird syntax highlighting might tip us off, but this code won’t run. The syntax seems valid enough, HTML elements aside. But we’ll get a message saying “unexpected token,” pointing us to our if statement.

奇怪的语法高亮显示可能会提示我们,但是此代码无法运行。 语法似乎足够有效,除了HTML元素。 但是我们会收到一条消息,提示“意外令牌”,将我们指向if语句。

You might know all this already. The React documentation prepares us for this outcome. Per the docs:

您可能已经知道所有这一切。 React文档为我们为实现这一结果做好了准备。 根据文档 :

if-else statements don’t work inside JSX. This is because JSX is just syntactic sugar for function calls and object construction. Take this basic example:

if-else语句在JSX中不起作用。 这是因为JSX只是函数调用和对象构造的语法糖。 举个基本的例子:

// This JSX:ReactDOM.render(<div id="msg">Hello World!</div>, mountNode);// Is transformed to this JS:ReactDOM.render(React.createElement("div", {id:"msg"}, "Hello World!"), mountNode);

This means that if statements don’t fit in…

这意味着if语句不适合…

This is a great start. JSX is syntactic sugar. It is HTML-like, but it isn’t HTML. When we used those div tags, we were really just calling React’s createElement function. Unfortunately, if you’re relatively new to JavaScript, as I am, this might not do anything to clear up the question of why if statements “don’t fit in.” Especially after we find out that this isn’t the end of conditional rendering. All we have to do is refactor a little bit.

这是一个很好的开始。 JSX是语法糖。 它类似于 HTML,但不是HTML。 当我们使用这些div标签时,我们实际上只是在调用React的createElement函数。 不幸的是,如果像我这样对JavaScript相对较新的人,这可能无法解决为什么 if语句“不适合”的问题。 特别是在我们发现这不是条件渲染的结束之后。 我们要做的只是重构一点。

This code compiles no problem. What gives? Why can we use the ternary operator and not an if-else statement? Isn’t the ternary operator just an if-else statement itself? The answer, apparently, is: sort of, but not really!

这段代码编译没问题。 是什么赋予了? 为什么我们可以使用三元运算符而不是if-else语句? 三元运算符本身不是if-else语句吗? 答案显然是:有点,但不是真的!

We got more of a clue from those React docs than it seems on the first read. “If statements don’t fit…”

从那些React文档中,我们获得的线索比一读时要多。 “如果陈述不适合……”

陈述与表达 (Statements vs. Expressions)

As it turns out, while the ternary (or conditional) operator does help us achieve the same functionality as if-else statements with fewer lines of code, there is an important distinction between the two. The standard if-else is a statement, whereas the ternary operator is an expression.

事实证明,尽管三元运算符(或条件运算符)确实帮助我们实现了与if-else语句具有相同功能的功能,但代码行较少,但是两者之间存在重要区别。 标准的if-else是一个语句 ,而三元运算符是一个表达式

An expression is any unit of code that evaluates to a value. 2 + 2 (arithmetic expression) is an expression. So is ‘hello world’ (string expression), 3 < 5 (logical expression), and sum = 4 (assignment expression). Since expressions evaluate to a value, we can use them anywhere a value is expected. This includes as an argument for a function invocation.

表达式是求值的任何代码单元。 2 + 2 (算术表达式)是一个表达式。 'hello world' (字符串表达式), 3 < 5 (逻辑表达式)和sum = 4 (赋值表达式)也是如此。 由于表达式求值,因此我们可以在需要值的任何地方使用它们。 这包括作为函数调用的参数。

By contrast, statements are instructions. They may contain expressions, but they are not required to return a value. A typical example might be variable declaration. If you type let sum = 4 into your browser's console, you get back "undefined." This is in contrast to our assignment expression sum = 4 which will return "4." Really, let sum = 4 is just telling the console "create a variable." It isn't an expression to be evaluated; it's an instruction to be executed. Because we aren't guaranteed a return value, we can't use statements in place of values. Thus we can't put statements in our function arguments.

相反,陈述是指令。 它们可以包含表达式,但是不需要返回值。 一个典型的例子可能是变量声明。 如果在浏览器的控制台中键入let sum = 4 ,则会返回“ undefined”。 这与我们的赋值表达式sum = 4 ,后者将返回“ 4”。 实际上, let sum = 4只是告诉控制台“创建变量”。 它不是要评估的表达式; 这是一条要执行的指令。 因为我们不能保证返回值,所以不能使用语句代替值。 因此,我们不能将语句放入函数参数中。

结论 (Conclusion)

So, JSX is syntactic sugar. When we write JSX, it gets changed into a standard JS function invocation. This limits us from using statements in our JSX (as an argument for the createElement function). However, we don’t have to use the ternary operator. We can handle any expression. This includes function calls and other logical operators. If we really wanted to use an if-else statement, all we’d have to do is wrap it in a function and pass the function as an argument. Also, the ternary vs. if-else debate assumes we are deciding between two elements to display. If we were only interested in rendering or not rendering a single element, we might use the && logical operator. You can find a fairly exhaustive list of alternatives for conditional rendering here.

因此,JSX是语法糖。 当我们编写JSX时,它变成了标准的JS函数调用。 这限制了我们不能在JSX中使用语句(作为createElement函数的参数)。 但是,我们不必使用三元运算符。 我们可以处理任何表达式。 这包括函数调用和其他逻辑运算符。 如果我们真的想使用if-else语句,我们所要做的就是将其包装在一个函数中并将该函数作为参数传递。 同样,三元与非其他辩论假设我们正在决定要显示的两个元素之间。 如果仅对呈现单个元素感兴趣,或者不呈现单个元素,则可以使用&&逻辑运算符。 您可以在此处找到相当详尽的条件渲染替代列表。

翻译自: https://medium.com/swlh/conditional-rendering-syntax-in-react-64d393811fa0

react 条件渲染


http://www.taodudu.cc/news/show-3125617.html

相关文章:

  • python关联规则apriori算法_Python --深入浅出Apriori关联分析算法(二) Apriori关联规则实战...
  • 关联规则与购物篮分析实战
  • python --深入浅出Apriori关联分析算法Apriori关联...
  • 人工智能洗衣机模糊推理系统实验(课本实验)
  • 理解Babel是如何编译JS代码的及理解抽象语法树(AST)
  • Association Rules_python关联规则
  • 关联规则----Apriori算法以及代码实现
  • 实现JavaScript语言解释器(二)
  • 六级考研单词之路-十二
  • android expandablelistview横向,Android ExpandableListView使用小结(一)
  • android自定义expandlistview,自定义ExpandableListView
  • 基于Thinkphp5+phpQuery 网络爬虫抓取数据接口,统一输出接口数据api
  • 《孙子兵法》与《战争论》对比
  • 从《亮剑》看先进的管理(原创)
  • 亮剑群英传
  • 从项目管理角度看马谡失街亭
  • 用Jupyter—Notebook爬取网页数据实例15(详讲selenium库)
  • 正规战和游击战
  • 李嘉图反例1
  • 战争磨盘十三:重整旗鼓
  • 战争磨盘十四:战争磨盘
  • 亮剑!(多图慎入)
  • 抗战电影中出场率很高的边三轮为什么能在软件界能混的风生水起
  • 推荐8部好看的抗日电视剧
  • 设计模式第一讲:单例模式(IBM开发者论坛已经发表的文章)
  • 在巨大的体量面前 华为是如何保持高效的战斗力的?
  • 给笔记本换电池18650锂电池\电池损耗
  • 笔记本电池只能充电到95%-99%之间无法充至100%的原因和处理方案
  • win10升级win11后笔记本电脑充不了电解决方法
  • 笔记本损耗60 计算机提示,笔记本买了一年 电池损耗已经60%了 怎么处理啊

react 条件渲染_React中的条件渲染语法相关推荐

  1. pandas使用query函数基于判断条件获得dataframe中满足条件的数据行(row)的索引列表(index of rows matching conditions in dataframe)

    pandas使用query函数基于判断条件获得dataframe中满足条件的数据行(row)的索引列表(index of rows matching conditions in dataframe) ...

  2. react大数据量渲染_React 中的状态自动保存(KeepAlive)

    什么是状态保存?假设有下述场景:移动端中,用户访问了一个列表页,上拉浏览列表页的过程中,随着滚动高度逐渐增加,数据也将采用触底分页加载的形式逐步增加,列表页浏览到某个位置,用户看到了感兴趣的项目,点击 ...

  3. 陈潇冰 react权威指南_React中条带化付款的分步指南

    陈潇冰 react权威指南 This is an adapted from several excerpts from Scott Hasbrouck's book, "The Node.j ...

  4. react回调函数_React中的回调中自动绑定ES6类函数

    在使用ES6类的React组件时,您必须遇到这种现象,必须显式绑定类函数,然后将其传递给诸如onClick.例如,采用以下示例. import React from 'react';class MyC ...

  5. r语言中对向量求条件语句_R中的条件语句

    r语言中对向量求条件语句 To advance with programming, we need to be able to control the flow of the program exec ...

  6. react 嵌套渲染_React 中嵌套数组数据如何渲染到前端页面

    现在有后端提供的类似下面这种格式的数据 { status:X, body: [ {year: 2017, month: [December, October, ...]} {year: 2016, m ...

  7. react 元素延迟加载_React中的延迟加载路线

    react 元素延迟加载 As developers, when we build apps for users on the internet, it is very important to en ...

  8. react同步请求_React中setState同步更新策略

    setState 同步更新 我们在上文中提及,为了提高性能React将setState设置为批次更新,即是异步操作函数,并不能以顺序控制流的方式设置某些事件,我们也不能依赖于this.state来计算 ...

  9. react取消捕获_React中阻止事件冒泡的问题详析

    前言 最近在研究react.redux等,网上找了很久都没有完整的答案,索性自己整理下,这篇文章就来给大家介绍了关于React阻止事件冒泡的相关内容,下面话不多说了,来一起看看详细的介绍吧 在正式开始 ...

最新文章

  1. 五年五件事,助我踏上寻梦路-追梦五年
  2. 面向对象 - 1.面向过程/2.面向对象/3.如何使用类/4.__init__方法/5.属性查找/6.补充知识/7.可扩展性高...
  3. Python中OpenCV2. VS. CV1
  4. 使用 HTML5 canvas 进行 Web 绘图
  5. 家里无线网络每天不定时段出现网速很慢或者直接无连接,这是怎么回事?
  6. 保存自动修复_CAD小技巧:怎样将自动保存的图形复原
  7. 它!5 年代替狂卷的 CNN!
  8. 【T+】畅捷通T+软件打印预览凭证或UFO生成报表 提示加载TBillOneCore.dll失败
  9. 彻底解决Missing privilege separation directory: /run/sshd
  10. 整理最全的图床集合——三千图床
  11. 机器学习-决策树算法
  12. C语言程序设计笔记(浙大翁恺版) 第七章:函数
  13. 测试用例优先级与三轮测试的结合
  14. 淘宝店铺装修之一怎样在自定义内容区做个商品图片轮播展示
  15. 全球与中国高氧潜水电脑市场深度研究分析报告
  16. Java程序的基本结构
  17. 台式计算机电源机箱维修,电脑机箱电源检测及修理办法
  18. Field ‘xxx‘ doesn‘t have a default value
  19. [前端bug词典]Already included file name ‘文件路径‘
  20. 2021年度总结:区块链农业技术领袖平台Dimitra

热门文章

  1. 计算机与英语教学相结合,计算机与英语教学结合_英语论文.doc
  2. 求职应聘时面试常见问题1
  3. es拼音分词 大帅哥_机器学习
  4. 有趣的搬砖工 No.2 cout格式化输出
  5. iOS 后台运行一段时间(不是地图,音乐类型APP)
  6. PSY 公式的 backtrader Indicator 实现
  7. 电信大型服务器机房_国内联通、电信、移动IDC机房名录
  8. 所谓的内存释放工具——原理
  9. 关于人们感知与数字视音频编码的关系入门-视觉篇01.
  10. excel表格如何转换成word表格_pdf的表格怎么转换成word?教你掌握重要一步