react实现vue动态组件
React 实现类似 Vue 动态组件功能
在 Vue 中可以通过 <component :is="currentComponent"> 动态切换组件,React 可以通过以下方式实现类似功能:
使用动态组件名渲染
通过对象映射组件名称与组件,利用对象属性访问动态选择组件:

const components = {
ComponentA: ComponentA,
ComponentB: ComponentB
};
function DynamicComponent({ componentName }) {
const SelectedComponent = components[componentName];
return <SelectedComponent />;
}
使用状态控制组件切换
通过 useState 维护当前显示的组件,实现动态切换:
function App() {
const [currentComponent, setCurrentComponent] = useState('ComponentA');
const components = {
ComponentA: <ComponentA />,
ComponentB: <ComponentB />
};
return (
<div>
<button onClick={() => setCurrentComponent('ComponentA')}>Show A</button>
<button onClick={() => setCurrentComponent('ComponentB')}>Show B</button>
{components[currentComponent]}
</div>
);
}
使用 React.createElement
通过 React.createElement 动态创建组件实例:

function DynamicRenderer({ componentName, props }) {
const componentMap = {
ComponentA,
ComponentB
};
return React.createElement(componentMap[componentName], props);
}
通过 children 传递动态组件
利用 props.children 实现更灵活的组件组合:
function Container({ children }) {
return <div className="container">{children}</div>;
}
function App() {
const [showA, setShowA] = useState(true);
return (
<Container>
{showA ? <ComponentA /> : <ComponentB />}
</Container>
);
}
使用 Context 实现全局组件切换
通过 Context 在应用任意层级控制显示组件:
const ComponentContext = React.createContext();
function ComponentProvider({ children }) {
const [CurrentComponent, setCurrentComponent] = useState(ComponentA);
return (
<ComponentContext.Provider value={{ CurrentComponent, setCurrentComponent }}>
{children}
</ComponentContext.Provider>
);
}
function ConsumerComponent() {
const { CurrentComponent } = useContext(ComponentContext);
return <CurrentComponent />;
}
这些方法都能实现类似 Vue 动态组件的功能,选择取决于具体场景需求。对象映射方式适合有限已知组件,Context 方案适合跨层级组件切换,children 方式则提供最大灵活性。






