首頁 > web前端 > js教程 > 主體

如何在 React/JSX 中動態渲染元件?

Mary-Kate Olsen
發布: 2024-11-15 14:12:02
原創
439 人瀏覽過

How to Dynamically Render Components in React/JSX?

Dynamic Component Rendering in React/JSX

React's JSX allows for declarative component rendering, but sometimes developers may need to dynamically render components based on their type.

The Issue

When attempting to render a component dynamically using the code snippet below, an error occurs:

var type = "Example";
var ComponentName = type + "Component";
return <ComponentName />; // Error: expected XML, got array
登入後複製

The error arises because the code uses array syntax while the JSX expects XML. Other solutions, such as creating a method for each component, are not elegant.

The Solution

The React documentation now provides an official solution for dynamic component rendering:

const MyComponent = Components[type + "Component"];
return <MyComponent />;
登入後複製

This code compiles to:

const MyComponent = Components[type + "Component"];
return React.createElement(MyComponent, {});
登入後複製

The variable MyComponent stores the component class and is capitalized. The React.createElement function then uses this class to create the component element.

以上是如何在 React/JSX 中動態渲染元件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板