In React, you can use dynamic tag names to create dynamically rendered components. Here's a common implementation:
import React from "react";
const DynamicComponent = ({ tag }) => {
const Tag = tag; // 将传入的标签名称赋值给一个变量
return <Tag>Hello, World!</Tag>; // 使用标签变量来渲染组件
};
const App = () => {
const tagName = "h1"; // 将要渲染的标签名称赋值给一个变量
return <DynamicComponent tag={tagName} />; // 将标签名称作为 props 传递给动态组件
};
export default App;
In the above example, we created a DynamicComponent
function component named. It receives an tag
attribute whose value is a tag name. Inside the component, we tag
assign the value of the property to a constant Tag
, and then use that constant in the returned JSX to render the corresponding tag.
In App
the component, we define a tagName
variable and assign it a value of "h1"
. We then pass it tagName
as tag
a property to DynamicComponent
the component. In this way, DynamicComponent
the component can dynamically render the corresponding component based on the incoming tag name.
You can also use other tag names as needed, such as "div"
, "p"
etc. Just assign the corresponding tag name to tagName
the variable.