Programming

매핑 할 객체 배열없이 React.js에서 요소를 반복하고 렌더링하는 방법은 무엇입니까?

procodes 2020. 6. 28. 20:03
반응형

매핑 할 객체 배열없이 React.js에서 요소를 반복하고 렌더링하는 방법은 무엇입니까?


jQuery 구성 요소를 React.js로 변환하려고하는데 문제가있는 것 중 하나는 for 루프를 기반으로 n 개의 요소를 렌더링하는 것입니다.

나는 이것이 불가능하거나 권장되며 모델에 배열이있는 경우 사용하는 것이 합리적이라는 것을 이해합니다 map. 괜찮습니다. 그러나 배열이 없을 때는 어떻습니까? 대신 렌더링 할 주어진 수의 요소와 같은 숫자 값을 가지면 어떻게해야합니까?

다음은 계층 구조 수준을 기준으로 임의의 수의 범위 태그가있는 요소를 접두사로 사용하려는 예입니다. 따라서 레벨 3에서는 텍스트 요소 앞에 3 개의 span 태그가 필요합니다.

자바 스크립트에서 :

for (var i = 0; i < level; i++) {
    $el.append('<span class="indent"></span>');
}
$el.append('Some text value');

JSX React.js 구성 요소에서 작동하거나 이와 비슷한 것을 얻을 수 없습니다. 대신 다음을 수행하여 먼저 임시 배열을 올바른 길이로 작성한 다음 배열을 반복해야했습니다.

React.js

render: function() {
  var tmp = [];
  for (var i = 0; i < this.props.level; i++) {
    tmp.push(i);
  }
  var indents = tmp.map(function (i) {
    return (
      <span className='indent'></span>
    );
  });

  return (
    ...
    {indents}
    "Some text value"
    ...
  );
}

확실히 이것이 최선이 아니거나 이것을 달성하는 유일한 방법은 아닐까요? 내가 무엇을 놓치고 있습니까?


업데이트 : React> 0.16

렌더 메소드가 반드시 단일 요소를 리턴 할 필요는 없습니다. 배열도 반환 할 수 있습니다.

var indents = [];
for (var i = 0; i < this.props.level; i++) {
  indents.push(<span className='indent' key={i}></span>);
}
return indents;

또는

return this.props.level.map((item, index) => (
    <span className="indent" key={index}>
        {index}
    </span>
));

JSX 어린이에 대해 설명하는 문서


낡은:

대신 하나의 루프를 사용할 수 있습니다

var indents = [];
for (var i = 0; i < this.props.level; i++) {
  indents.push(<span className='indent' key={i}></span>);
}
return (
   <div>
    {indents}
    "Some text value"
   </div>
);

.map 및 fancy es6을 사용할 수도 있습니다

return (
   <div>
    {this.props.level.map((item, index) => (
       <span className='indent' key={index} />
    ))}
    "Some text value"
   </div>
);

또한 반환 값을 컨테이너에 싸야합니다. 위 예제에서 div를 사용했습니다.

워드 프로세서가 말하는 것처럼 여기

Currently, in a component's render, you can only return one node; if you have, say, a list of divs to return, you must wrap your components within a div, span or any other component.


Here is more functional example with some ES6 features:

'use strict';

const React = require('react');

function renderArticles(articles) {
    if (articles.length > 0) {      
        return articles.map((article, index) => (
            <Article key={index} article={article} />
        ));
    }
    else return [];
}

const Article = ({article}) => {
    return ( 
        <article key={article.id}>
            <a href={article.link}>{article.title}</a>
            <p>{article.description}</p>
        </article>
    );
};

const Articles = React.createClass({
    render() {
        const articles = renderArticles(this.props.articles);

        return (
            <section>
                { articles }
            </section>
        );
    }
});

module.exports = Articles;

I'm using Object.keys(chars).map(...) to loop in render

// chars = {a:true, b:false, ..., z:false}

render() {
    return (
       <div>
        {chars && Object.keys(chars).map(function(char, idx) {
            return <span key={idx}>{char}</span>;
        }.bind(this))}
        "Some text value"
       </div>
    );
}

Array.from() takes an iterable object to convert to an array and an optional map function. You could create an object with a .length property as follows:

return Array.from({length: this.props.level}, (item, index) => 
  <span className="indent" key={index}></span>
);

I think this is the easiest way to loop in react js

<ul>
    {yourarray.map((item)=><li>{item}</li>)}
</ul>

참고URL : https://stackoverflow.com/questions/29149169/how-to-loop-and-render-elements-in-react-js-without-an-array-of-objects-to-map

반응형