source

JSX 요소를 어레이에 연결하려면 어떻게 해야 합니까?

itover 2023. 3. 18. 08:32
반응형

JSX 요소를 어레이에 연결하려면 어떻게 해야 합니까?

리액트 월드에서 짜증나는 시간...특정 기준에 따라 마크업을 작성할 수 있어야 합니다.예를 들어, 저는 일련의 아이템을 받습니다.이 항목들을 확인하고 기준에 따라 다른 마크업을 생성해야 합니다.예를 들어, 다음과 같은 항목의 배열을 수신하는 함수가 있습니다.

processItems(itemArray) {
    // Create an empty array that will hold the final JSX output.
    let buffer = []

    // Somehow push the first required markup into the buffer.
    buffer.push(<div className"container flex center">);

    // ... here we do a switch statement that evaluates each item in the 'itemArray' argument and based on that I create different <div className="XYZ">{...put stuff here...}</div> markup, which I will push into the buffer - which will contain the final JSX output...

    // Now I close the initial container element
    buffer.push(</div>);

    // And return the buffer for display inside the render() function
    return buffer;
}

문제는 간단히 할 수 없다는 것이다.array.push()리액션이 마음에 들지 않아서 배열에 개별 마크업을 추가하는 것, 그리고 결국엔 횡설수설한 표시로 끝나게 될 것이다.

내가 어떻게 이럴 수 있지?

솔루션은 다음과 같습니다.

processItems(itemArray) {
    // Create an empty array that will hold the final JSX output.
    let buffer = []

    buffer.push(<div>A</div>);
    buffer.push(<div>B</div>);
    buffer.push(<div>C</div>);


    // And return the buffer for display inside the render() function
    return (
        <div className"container flex center">
            {buffer}
        </div>
    );
}

JSX는 HTML이 아니기 때문에 HTML 요소를 여러 단계로 조합할 수 없습니다.

언급URL : https://stackoverflow.com/questions/40476075/how-to-concatenate-jsx-elements-into-an-array

반응형