컴포넌트의 렌더 어레이를 리액트
질문 하나 할게요.컴포넌트 배열 렌더링 할 줄 아는 사람?개발자가 특정 컴포넌트를 쉽게 변경할 수 있도록 합니다.(대시보드 같은 거죠)
컴포넌트 리스트파일
import React from 'react';
export default [
<ComponentOne/>
<ComponentTwo/>
];
대시보드 컴포넌트
import React from 'react';
import components from './../../components';
export default class Dashboard extends React.Component
{
render = () => {
//Want to render the array of components here.
return (
<div className="tile is-parent">
{components}
</div>
);
};
}
문제는 키를 추가해야 하는 컴포넌트 배열이 있다는 것입니다.하지만!컴포넌트에도 키를 추가할 수 없는 것 같습니다.설명을 어떻게 해야 할지 잘 모르기 때문에 시도해 본 코드는 다음과 같습니다.
{components.map((component, key) => (
<component key={key}/>
}
위의 작업을 수행해도 아무것도 렌더링되지 않지만 '키를 적용해야 합니다' 오류가 표시되지 않습니다.그리고 '컴포넌트'가 존재하지 않거나 그런 식으로 이상한 것이 있기 때문이라고 생각합니다.
나도 해봤어component.key = key;
이런 종류의 물체에서는 그렇게 할 수 없는 것 같아요?
대체적으로 배열 대신 단축 함수를 반환해야 하는데 어떤 이유로 배열이 마음에 드나요?후배들한테는 더 간단한 것 같아.
새로운 리액트 프래그먼트(Respact Fragments(v16의 경우)
이것은 어레이/키 문제 전체를 해결할 수 있는 가장 간단한 해결책입니다.
키를 넘겨야 한다면 컴포넌트에 키를 달도록 하는 것이 좋습니다.React는 이렇게 동작하기 때문에 예측할 수 없는 인터페이스 뒤에 이 동작을 숨기는 것은 권장하지 않습니다.
이 작업을 꼭 수행해야 하는 경우 를 사용하여 요소를 복제하고 새 속성을 주입할 수 있습니다.
React.cloneElement(element, { key: 'foo' });
컴포넌트 파일의 모든 컴포넌트를 항상 렌더링하려면 React로 랩하는 것이 좋습니다.fragments 태그가 붙습니다.
베스트 프랙티스는 이 기능을 상수가 아닌 컴포넌트를 반환하는 단순한 함수로 내보내는 것입니다.
그래서...
const Components = props => {
return (
<React.Fragment>
<ComponentOne/>
<ComponentTwo/>
</React.Fragment>
)
}
export default Components
이를 통해 여러 컴포넌트를 포함하는 DOM 요소 없이 여러 컴포넌트를 나란히 배치할 수 있습니다.
그런 다음 일반 컴포넌트로 사용하면 모든 컴포넌트가 렌더링되므로 Import만 하면 됩니다.
<Components />
그렇지 않으면 어레이처럼 처리하려면 Import한 React 개체에서 무료로 기능을 사용할 수 있습니다.
React.Children.toArray(arrayOfComponents)
컴포넌트 배열(원래 질문에서와 같이)을 전달하면 필요에 따라 정렬하고 슬라이스할 수 있습니다.그러면 렌더링 함수의 반환으로 드롭할 수 있습니다.
제 코멘트를 팔로우 해 주시면 감사하겠습니다.
{components.map((component, index) => (
<span key={index}>
{ component }
</span>
}
에서는 React 16을 사용할 수 .React.Fragment
:
{components.map((component, index) => (
<React.Fragment key={index}>
{ component }
</React.Fragment>
}
이 답들은 거의 모두 옳다.요.<../>
★★★★★★★★★★★★★★★★★★:
export default [
ComponentOne,
ComponentTwo,
]
다른 에는 ''를 사용합니다..map()
:
export default class Dashboard extends React.Component {
render = () => (
<div className="tile is-parent">
{components.map((Component, key) => (<Component key={key} />))}
</div>
)
}
, 「 」, 「 」를 사용하는 는, 의 점에 해 주세요.Fragment
이 제안하는 처럼 그냥 ''라고 쓰면 됩니다.<>...</>
★★★★★★ 。
컴포넌트를 쉽게 정리할 수 있습니다.div
key
아래에 기재한 바와 같이
const Example = ({components}) => (
<div>
{components.map((component, i) => <div key={i}>{component}</div>)}
</div>
)
실제로 다음 배열을 내보내고 있습니다.elements
파일을 참조해 주세요. 방법은 컴포넌트 배열을 것입니다.
import React from 'react';
export default [
ComponentOne
ComponentTwo
];
// Then following will work
{components.map((Component, key) => (
// Remember to make first letter capital (in this case "c")
<Component key={key}/>
}
은 그 예요.div
import React from 'react';
export default [
<ComponentOne/>
<ComponentTwo/>
];
// Then wrap in div
{components.map((component, key) => (
<div key={key}>
{component}
</div>
}
다음과 같이 할 수도 있습니다.
{components.map(component => component)}
컴포넌트가 하나씩 표시되도록 매핑됩니다.
그냥 좀 더 많은 대답을 받아들이기 위해서.요소 배열이 있는 경우elementArray
이런 ...
컴포넌트 어레이를 작성하려면 -
elementArray.push(<MyComponent/>);
그리고 렌더링에서...
<div>
{
elementArray.map((element,i) => {
React.cloneElement(element, { key: i, onClick: () => myOnclick(i)})
})
}
</div>
의 두 번째 .React.cloneElement
렌더링 시 컴포넌트에 전달할 모든 소품의 객체입니다.
react version 16 이상의 버전을 사용하는 경우 다음과 같이 컴포넌트 목록을 작성할 수 있습니다.
import React from 'react';
export const componentList = [ ComponentOne, ComponentTwo ];
그런 식으로 아무데나 렌더링할 수 있습니다.
import React from 'react';
function SomeComponent() {
return (
<div>
{componentList.map((component, index) => (
<div key={index}> {component && component.render()}</div>
))}
</div>
);
}
컴포넌트를 어레이 내에 배치하는 경우는, 통상, 다음과 같이 실시합니다.
const COMPONENTS = [
<Foo />,
<Bar />
]
[0, 1].map(item => {
return (
<React.Fragment key={item}>
{COMPONENTS[item]}
</React.Fragment>
)
})
언급URL : https://stackoverflow.com/questions/48131100/react-render-array-of-components
'programing' 카테고리의 다른 글
iPhone/iOS JSON 해석 튜토리얼 (0) | 2023.03.08 |
---|---|
Ajax를 사용하여 JSON을 PHP로 보내는 중 (0) | 2023.03.08 |
텍스트 입력에서 ng-change가 작동하지 않음 (0) | 2023.03.08 |
angularjs 형식 재설정 오류 (0) | 2023.03.08 |
대응: 기존 컴포넌트에 소품 추가 (0) | 2023.03.08 |