jsx 里获取元素_为什么您不能返回并行JSX元素。 哈克!
jsx 里获取元素
答案 ( The Answer )
JavaScript as a language doesn’t support multiple return values. In writing React code, your JSX (JavaScript XML) eventually gets transpiled into vanilla JavaScript. When this happens, parallel JSX elements are transpiled into multiple return values which isn’t a feature supported by the language(JavaScript).
JavaScript作为一种语言不支持多个返回值。 在编写React代码时,您的JSX(JavaScript XML)最终将被转换为原始JavaScript。 发生这种情况时,并行JSX元素将转换为多个返回值,而该返回值不是该语言(JavaScript)所支持的功能。
更深入地研究返回语句,JavaScript和JSX ( A Deeper Dive into Return Statements, JavaScript and JSX )
If you’ve written React for quite sometime, you probably have noticed an error of this sort that occurs whenever you try to return more than one element from a React component i,e
如果您已经写了React很久了,那么您可能会发现,当您尝试从React组件i,e返回多个元素时会发生此类错误。
import React from 'react'const Loading = () => {return (<p>Another parent element</p><div className="text-center"><i className="fas fa-spinner fa-3x"></i><h4 className="mb-3">This may take a few seconds. Please wait!</h4><p>Loading....</p></div>)
}
export default Loading Why does this occur? And what does it really mean?
为什么会发生这种情况? 这到底是什么意思?
To find the answers, let’s briefly examine how return statements work in Javascript.
为了找到答案,让我们简要地检查一下return语句如何在Javascript中工作。
退货单 ( Return Statements )
In JavaScript, the return statement is used to terminate a function’s execution and return a single value from the function. This single value could be a string, number, array, object, function etc.
在JavaScript中,return语句用于终止函数的执行并从函数返回单个值 。 该单个值可以是字符串,数字,数组,对象,函数等。
The only condition is that it must evaluate to a value. Otherwise undefined is return from the function.
唯一的条件是它必须求值。 否则,从函数返回undefined。
Here’s a typical example:
这是一个典型的例子:
function sum(a, b) {return a + b
} More information about return statements can be found here on the Mozilla Developer Network.
可在Mozilla开发人员网络上找到有关返回语句的更多信息。
Notice that a return statement terminates the execution of a function. This makes code as shown below flawed as the latter statement can never be reached once the first return statement is executed.
请注意,return语句终止函数的执行。 这使得如下所示的代码存在缺陷,因为一旦执行了第一个return语句,就永远无法到达后一个语句。
function sumAndDifference(a, b) {return a + breturn a - b
} OR
要么
function sumAndDifference(a, b) {return a + b, a - b
} A typical solution to this problem in JavaScript would be to group return statements into collections that can be de-structured at a later point.
JavaScript中此问题的典型解决方案是将return语句分组为可在以后进行重构的集合。
function sumAndDifference(a, b) {return [a + b, a - b]
} OR
要么
function sumAndDifference(a, b) {return {sum: a + b,difference: a - b}
} This behaviour is what is common across many modern programming languages. Although, some programming languages like “Go” have ways of implementing multiple return statements, in many cases the idea comes down to grouping the items as one unit that can be de-structured when the returned values are needed.
这种行为是许多现代编程语言中常见的行为。 尽管某些编程语言(如“ Go”) 具有实现多个返回语句的方式,但在许多情况下,想法归结为将项目分组为一个单位,当需要返回值时可以将其分解。
JavaScript符合JSX ( JavaScript meets JSX )
When React components created using JSX get transpiled into vanilla JavaScript, we basically end up with functions that return some constructed markup to be injected into the DOM. See a typical example below:
当使用JSX创建的React组件被转换为原始JavaScript时,我们基本上得到了一些函数,这些函数返回一些构造好的标记以注入到DOM中。 请参见下面的典型示例:
React code
React代码
import React from 'react'const Loading = () => {return(<div className="text-center"><i className="fas fa-spinner fa-3x"></i><h4 className="mb-3">This may take a few seconds. Please wait!</h4><p>Loading....</p></div>)
}export default Loading Transpiled Vanilla JavaScript
转译的香草JavaScript
"use strict";Object.defineProperty(exports, "__esModule", {value: true
});
exports.default = void 0;var _react = _interopRequireDefault(require("react"));function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }var Loading = function Loading() {return _react.default.createElement("div", {className: "text-center"}, _react.default.createElement("i", {className: "fas fa-spinner fa-3x"}), _react.default.createElement("h4", {className: "mb-3"}, "This may take a few seconds. Please wait!"), _react.default.createElement("p", null, "Loading...."));
};var _default = Loading;
exports.default = _default; Notice how the function Loading above returns some markup created from a series of nested elements constructed via React’s createElement method.
注意上面的Loading函数如何返回一些标记,这些标记是通过React的createElement方法构造的一系列嵌套元素创建的。
仔细研究JSX移植 ( A closer look at the JSX transpilation )
Let’s now take a closer look at the JSX conversion that took place above:
现在,让我们仔细看看上面发生的JSX转换:
React.createElement("div", {className: "text-center"
}, React.createElement("i", {className: "fas fa-spinner fa-3x"
}), React.createElement("h4", {className: "mb-3"
}, "This may take a few seconds. Please wait!"), React.createElement("p", null, "Loading....")); Without all the other things that make up a React component, the JSX earlier written translates into the code above. As the React documentation clearly states:
由于没有其他所有组成React组件的内容,因此先前编写的JSX可以转换为上面的代码。 正如React文档明确指出的那样 :
createElement() creates and returns a new React element of the given type. The type argument can be either a tag name string (such as 'div' or 'span'), a React component type (a class or a function), or a React fragment type.
createElement()创建并返回给定类型的新React元素 。 type参数可以是标签名称字符串(例如'div'或'span'), React组件类型(类或函数)或React片段类型。
It accepts parameters as shown below:
它接受如下所示的参数:
React.createElement(type,[props],[...children]
) At conversion, this method is used to recreate the markup originally written in JSX, and then the markup is returned from the function. Notice that in the example above, there is only one enclosing element returned from the React component’s render function. Thus, the transpiled JSX has only one return value which nests every other element enclosed by the parent element.
转换时,此方法用于重新创建最初用JSX编写的标记,然后从该函数返回标记。 请注意,在以上示例中,React组件的render函数仅返回一个封闭元素。 因此,已编译的JSX仅具有一个返回值,该返回值嵌套在父元素包围的所有其他元素中。
What happens when there is more than one enclosing element? When there is more than one enclosing element, the transpiled function tends to have two return values(one for each enclosing element). See example below:
如果有一个以上的封闭元素会发生什么? 如果有一个以上的包围元素,则已编译的函数趋向于具有两个返回值(每个包围元素一个)。 请参见下面的示例:
React Code
React代码
import React from 'react'const Loading = () => {return(<p>Another parent element</p><div className="text-center"><i className="fas fa-spinner fa-3x"></i><h4 className="mb-3">This may take a few seconds. Please wait!</h4><p>Loading....</p></div>)
}
export default Loading Transpiled Vanilla JavsScript
转译的香草JavsScript
"use strict";Object.defineProperty(exports, "__esModule", {value: true
});
exports.default = void 0;var _react = _interopRequireDefault(require("react"));function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }var Loading = function Loading() {return _react.createElement("p", {}, "Another parent element"),_react.default.createElement("div", {className: "text-center"}, _react.default.createElement("i", {className: "fas fa-spinner fa-3x"}), _react.default.createElement("h4", {className: "mb-3"}, "This may take a few seconds. Please wait!"), _react.default.createElement("p", null, "Loading...."));
};var _default = Loading;
exports.default = _default; Notice that in the transpiled code, the function Loading now has multiple return values in the format return a,b.
注意,在已编译的代码中,函数Loading现在具有多个返回值,格式为return a,b 。
This would result in an error as this is unsupported in JavaScript, thus unsupported in JSX(JavaScript XML).
这将导致错误,因为JavaScript不支持,因此JSX(JavaScript XML)不支持。
这是使用并行JSX Elements的解决方案 ( Here’s the Solution to working with Parallel JSX Elements )
Recall that with vanilla JS, solving this problem would require that you group the statements to be returned into a collection of some sort so that it is treated as one value.
回想一下,使用香草JS,要解决此问题,将需要将要返回的语句分组为某种类型的集合,以便将其视为一个值。
1 . Wrapping all markup in an extra element An ideal way to do this in JSX would be to group the elements, by adding an extra wrapping element that encloses all markup. See example below:
1。 将所有标记包装在一个额外的元素中JSX中实现此目的的理想方法是通过添加一个包含所有标记的额外包装元素来对元素进行分组。 请参见下面的示例:
import React from 'react'const Loading = () => {return (<div><p>Another parent element</p><div className="text-center"><i className="fas fa-spinner fa-3x"></i><h4 className="mb-3">This may take a few seconds. Please wait!</h4><p>Loading....</p></div></div>)
}export default Loading As much as this solves the problem, in some cases you can’t afford to add an extra node to the DOM as it may mess up your styling or page layout. This leads us to the second solution.
尽管这可以解决问题,但在某些情况下,您无力向DOM添加额外的节点,因为这可能会破坏您的样式或页面布局。 这将我们引向第二个解决方案。
2. Using React Fragment React Fragment is used to group a list of child elements without adding extra nodes to the DOM. See example below:
2.使用React Fragment React Fragment用于对子元素列表进行分组,而无需向DOM添加额外的节点。 请参见下面的示例:
import React, { Fragment } from 'react'const Loading = () => {return (<Fragment><p>Another parent element</p><div className="text-center"><i className="fas fa-spinner fa-3x"></i><h4 className="mb-3">This may take a few seconds. Please wait!</h4><p>Loading....</p></div></Fragment>)
}export default Loading This creates a container element such that when the code is transpiled it is wrapped within a React fragment which does not add an extra node on injection into the DOM. It has a shorthand syntax which makes use of empty tags as shown below:
这将创建一个容器元素,以便在编译代码时将其包装在React片段中,该片段不会在注入DOM时添加额外的节点。 它具有简化的语法,该语法使用空标签,如下所示:
import React from 'react'const Loading = () => {return (<><p>Another parent element</p><div className="text-center"><i className="fas fa-spinner fa-3x"></i><h4 className="mb-3">This may take a few seconds. Please wait!</h4><p>Loading....</p></div></>)
}export default Loading 结论 ( Conclusion )
Here’s what we learned in this article:
这是我们从本文中学到的内容:
- JavaScript does not support multiple return values. JavaScript不支持多个返回值。
- JSX in React is transpiled to vanilla JS which uses React’s
createElement()method to compose the markup as outlined using JSX. React中的JSX被转换为香草JS,后者使用React的createElement()方法来组成标记,如使用JSX概述的那样。 - When you return parallel JSX elements from a Component’s render function in React, the code gets transpiled into a function that returns multiple values which is not supported in JavaScript. 当您从React中的Component的render函数返回并行JSX元素时,代码将被转换为一个函数,该函数返回JavaScript不支持的多个值。
- To solve this problem, you can either use a wrapping element to enclose all markup or use React Fragments in cases where you cannot afford to inject any extra nodes into the DOM. 为了解决这个问题,您可以使用包装元素将所有标记括起来,或者在无法负担向DOM中注入任何额外节点的情况下使用React Fragments。
翻译自: https://scotch.io/tutorials/why-you-cant-return-parallel-jsx-elements-the-hack
jsx 里获取元素
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
