React의 다른 return 문에서 JSX 여러 줄을 반환하는 방법은 무엇입니까?
한 줄이 잘 작동합니다.
render: function () {
return (
{[1,2,3].map(function (n) {
return <p>{n}</p>
}}
);
}
여러 줄이 아님
render: function () {
return (
{[1,2,3].map(function (n) {
return (
<h3>Item {n}</h3>
<p>Description {n}</p>
)
}}
);
}
감사.
태그를 함수 호출로 생각하십시오 ( docs 참조 ). 그런 다음 첫 번째는 다음과 같습니다.
{[1,2,3].map(function (n) {
return React.DOM.p(...);
})}
그리고 두 번째 :
{[1,2,3].map(function (n) {
return (
React.DOM.h3(...)
React.DOM.p(...)
)
})}
이제 두 번째 스 니펫이 실제로 의미가 없다는 것이 분명합니다 (JS에서 둘 이상의 값을 반환 할 수 없음). 다른 요소 (원하는 것, 유효한 key
속성을 제공 할 수도 있음)로 래핑 하거나 다음과 같이 사용할 수 있습니다.
{[1,2,3].map(function (n) {
return ([
React.DOM.h3(...),
React.DOM.p(...)
]);
})}
JSX 설탕 사용 :
{[1,2,3].map(function (n) {
return ([
<h3></h3>, // note the comma
<p></p>
]);
})}
결과 배열을 평평하게 할 필요가 없습니다. React가 대신 할 것입니다. 다음 바이올린 http://jsfiddle.net/mEB2V/1/을 참조하십시오 . 다시 말하지만, 두 요소를 div / 섹션으로 래핑하는 것이 장기적으로 더 좋습니다.
배열 반환에 대한 오래된 답변이 더 이상 적용되지 않는 것 같습니다 (@ dogmatic69 가 주석에 썼 듯이 React ~ 0.9 이후 ).
문서 에서는 단일 노드를 반환해야한다고 말합니다.
최대 JSX 루트 노드 수
현재 구성 요소의 렌더링에서 하나의 노드 만 반환 할 수 있습니다. 예를 들어 반환 할 div 목록이있는 경우 구성 요소를 div, 범위 또는 기타 구성 요소로 래핑해야합니다.
JSX가 일반 JS로 컴파일된다는 것을 잊지 마십시오. 두 함수를 반환하는 것은 실제로 구문 상 의미가 없습니다. 마찬가지로 삼항에 둘 이상의 자식을 넣지 마십시오.
대부분의 경우 간단히 a <div>
또는 <span>
.
제 경우에는 여러 <tr>
s 를 반환하고 싶었습니다 . 나는 그것들을 포장했습니다 <tbody>
– 테이블은 여러 개의 몸체를 가질 수 있습니다.
EDIT: As of React 16.0, returning an array is apparently allowed again, as long as each element has a key
: https://facebook.github.io/react/blog/2017/09/26/react-v16.0.html#new-render-return-types-fragments-and-strings
EDIT: React 16.2 lets you surround a list of elements with <Fragment>…</Fragment>
or even <>…</>
, if you prefer that to an array: https://blog.jmes.tech/react-fragment-and-semantic-html/
From React v16.0.0 onwards, it is possible to Return multiple elements by wrapping them within an Array
render() {
return (
{[1,2,3].map(function (n) {
return [
<h3>Item {n}</h3>.
<p>Description {n}</p>
]
}}
);
}
Also from React v16.2.0, a new feature called React Fragments
is introduced which you can use to wrap multiple elements
render() {
return (
{[1,2,3].map(function (n, index) {
return (
<React.Fragment key={index}>
<h3>Item {n}</h3>
<p>Description {n}</p>
</React.Fragment>
)
}}
);
}
As per the documentation:
A common pattern in React is for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM.
Fragments declared with the explicit syntax may have keys. A use case for this is mapping a collection to an array of fragments — for example, to create a description list:
function Glossary(props) { return ( <dl> {props.items.map(item => ( // Without the `key`, React will fire a key warning <React.Fragment key={item.id}> <dt>{item.term}</dt> <dd>{item.description}</dd> </React.Fragment> ))} </dl> ); }
key is the only attribute that can be passed to Fragment. In the future, we may add support for additional attributes, such as event handlers.
Also, you might want to return several list items in some helper function inside a React component. Just return an array of html nodes with the key
attribute:
import React, { Component } from 'react'
class YourComponent extends Component {
// ...
render() {
return (
<ul>
{this.renderListItems()}
</ul>
)
}
renderListItems() {
return [
<li key={1}><a href="#">Link1</a></li>,
<li key={2}><a href="#">Link2</a></li>,
<li key={3} className="active">Active item</li>,
]
}
}
You can use createFragment
here.
https://facebook.github.io/react/docs/create-fragment.html
import createFragment from 'react-addons-create-fragment';
...
{[1,2,3].map((n) => createFragment({
h: <h3>...</h3>,
p: <p>...</p>
})
)}
(using ES6 and JSX syntax here)
you first have to add the react-addons-create-fragment
package :
npm install --save react-addons-create-fragment
Advantage over Jan Olaf Krems's solution : react does not complain about the missing key
Updated
Use React Fragment. It's simple. Link to fragment documentation.
render() {
return (
<>
{[1,2,3].map((value) => <div>{value}</div>)}
</>
);
}
Old answer - obsolete
With React > 16 you can use react-composite.
import { Composite } from 'react-composite';
// ...
{[1,2,3].map((n) => (
<Composite>
<h2>Title {n}</h2>
<p>Description {n}</p>
</Composite>
))};
Of course, react-composite has to be installed.
npm install react-composite --save
'program tip' 카테고리의 다른 글
바이너리 파일 읽기 및 쓰기 (0) | 2020.09.03 |
---|---|
Javascript 객체 값을 동적으로 설정하는 방법은 무엇입니까? (0) | 2020.09.03 |
오류 5 : Windows 서비스를 시작할 때 액세스가 거부되었습니다. (0) | 2020.09.03 |
Razor를 사용한 Html.RenderPartial () 구문 (0) | 2020.09.03 |
Underscore.js와 jQuery는 서로를 보완합니까? (0) | 2020.09.03 |