React dynamic tag name

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 DynamicComponentfunction component named. It receives an tagattribute whose value is a tag name. Inside the component, we tagassign the value of the property to a constant Tag, and then use that constant in the returned JSX to render the corresponding tag.

In Appthe component, we define a tagNamevariable and assign it a value of "h1". We then pass it tagNameas taga property to DynamicComponentthe component. In this way, DynamicComponentthe 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 tagNamethe variable.

Guess you like

Origin blog.csdn.net/m0_74265396/article/details/135434041