React의 동적 구성 요소
8330 단어 opensourcereactjavascriptwebdev
소개
안녕하세요. Vue로 작업한 적이 있다면 아래와 같이
component 태그를 통해 구성 요소를 동적으로 사용할 수 있다는 것을 알게 될 것입니다.<script>
import CustomComponent from 'path-to-custom-component'
import AnotherComponent from 'path-to-another-component'
export default {
components: {CustomComponent, AnotherComponent},
data() {
return {
activeComponent: 'CustomComponent'
}
}
}
</script>
<template>
<div>
<component :is="activeComponent" />
</div>
</template>
이 기사에서는 React에서 구성 요소를 동적으로 사용하는 방법을 시연합니다.
코딩을 시작하자
이미 반응 프로젝트가 설정되어 있다고 가정하고 바로 시작하겠습니다.
먼저 아직 없는 경우 루트 디렉터리에
components 폴더를 만듭니다.components 폴더 안에 DynamicComponent.js라는 새 파일을 만들고 다음 코드를 추가합니다.import React from "react";
/**
* @desc the dynamic component is used to render various component dynamically
* @params props: {
* useDefaultPath: this indicates that the component to be used is in the components folder if set to true else you would have to pass in a different component
* is: if `useDefaultPath` is true, you pass in the name of the component file or the path to the component in the component folder eg: NewComponent or BaseUI/NewComponent
* ...rest: the props to be passed into the new component
* }
*/
const DynamicComponent = ({ is, useDefaultPath = true, ...rest }) => {
return React.createElement(
useDefaultPath ? require(`./${is}.js`).default : is,
{
...rest,
}
);
};
export default DynamicComponent;
이제 다른 파일에서 이 구성 요소를 사용하여 설정한 조건에 따라 다른 구성 요소를 동적으로 렌더링할 수 있습니다.
예는 아래 코드입니다.
import "./App.css";
import DynamicComponent from "./components/DynamicComponent";
import { useState } from "react";
function App() {
const [activeComponent, setActiveComponent] = useState("SayHello");
return (
<div className="App">
<header className="App-header">
<DynamicComponent is={activeComponent} name="Sholademi Ayomikun" />
<button
onClick={() =>
// Note that `SayHello` and `SayGoodbye` have been defined in the components folder
setActiveComponent(
activeComponent === "SayHello" ? "SayGoodbye" : "SayHello"
)
}
>
Toggle Component
</button>
</header>
</div>
);
}
export default App;
결론
이 문서에서는
React.createElement를 사용하여 구성 요소를 동적으로 렌더링하는 방법을 보여줍니다. 이에 대한 코드는 here에서 찾을 수 있습니다.사용 사례는 앱 레이아웃을 동적으로 변경하거나 보기가 다른 여러 탭을 갖는 것입니다.
React에서 이를 수행하는 방법에는 여러 가지가 있습니다.
나를 팔로우하고 github
또한 구독하십시오. 최대 50명의 구독자를 확보하여 거기에서 콘텐츠를 제공하려고 합니다.
Reference
이 문제에 관하여(React의 동적 구성 요소), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/ayo_tech/how-to-use-components-dynamically-in-react-2gmk텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)