Dynamic Components
This is a component adapted to Vue's <component :is="...">, implemented in React via <Component is={...} /> for dynamic rendering. It supports conditional switching of component types, native tags, and created React elements.
Basic Usage
Specify the component type to be rendered dynamically via the is prop, which can be easily used in scenarios such as tabs and view switching.
Core usage example:
const [currentTab, setCurrentTab] = useState('Post');
const tabs = {
Post: PostView,
Archive: ArchiveView,
};
<Component is={tabs[currentTab]} />;Please note:
The transition effect when switching DOM in the example is not built into the
<Component>component.
Render Native Tags
is can also be a string tag name, and the passed props will be forwarded to the final rendered native node.
const [tag, setTag] = useState('button');
<Component
is={tag}
className="custom-element"
title="Forwarded Title"
href={tag === 'a' ? '#' : undefined}
>
Dynamic Tag Content
</Component>;Usage with KeepAlive
When using dynamic components with <KeepAlive>, it is recommended to provide a stable key for child nodes to ensure correct caching and switching.
const [tab, setTab] = useState('Input');
const components = {
Input: InputView,
Counter: CounterView,
};
<KeepAlive>
<Component is={components[tab]} key={tab} />
</KeepAlive>;API
Props
interface ComponentProps extends Record<string, any> {
/**
* Target for dynamic rendering.
* Supports native tag names, component types, and ReactElement.
*/
is: string | ComponentType<any> | ReactElement;
}Notes
- When
isis an invalid value, the component returnsnulland outputs an error log. - When
isis aReactElement, new props will be merged during cloning, and the externally passedchildrenwill be used first. - When used with cached components, prioritize using a stable
keyto avoid state confusion during switching.
