簡體   English   中英

動態渲染字符串數組中的組件

[英]Dynamically rendering react components from string array

當反應代碼中的CMS退出時,會動態地出現問題以呈現組件。

將變量名解析為一個數組以在實際渲染中使用時沒有問題-但無論我使用哪種方法,這里都會收到錯誤:

  • 警告:正在使用大寫HTML。 在React中始終使用小寫的HTML標簽。
  • 警告:正在使用大寫HTML。 在React中始終使用小寫的HTML標簽。

清楚表明我正在使用大寫字母:)

 import React, { Component } from 'react'; import { createClient } from 'contentful'; import CtaBlock from './CTABlock'; import DeviceList from './DeviceList'; class HomeContainer extends Component { constructor(props) { super(props); this.state = { pageCont: [], entries: [] }; } componentDidMount() { const client = createClient({ // This is the space ID. A space is like a project folder in Contentful terms space: '...', // This is the access token for this space. Normally you get both ID and the token in the Contentful web app accessToken: '...' }); client.getEntries({ 'sys.id': '5stYSyaM8gkiq0iOmsOyKQ' }).then(response => { this.setState({ mainCont: response }); }); } getEntries = pageCont => { var linkedEntries = pageCont.includes.Entry; console.log(linkedEntries); return linkedEntries; }; render() { var formattedComponents = []; var renderedComponents = []; if (this.state.mainCont) { //getting the type of component from the Contetful API (String) var componentList = this.getEntries(this.state.mainCont).map(entries => entries.sys.contentType.sys.id); //converting the component names to upper case formattedComponents = componentList.map(comps => comps.charAt(0).toUpperCase() + comps.slice(1)); renderedComponents = formattedComponents.map(MyComponent => { return <MyComponent / > }); } return ( <div> <h1> Dynamically Generated Components Div </h1> {renderedComponents} </div> ); } } export default HomeContainer; 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> Appreciate any insight! 

當我了解您的權利時,您想要存檔的是將字符串鍵映射到某個組件的權利,對嗎?

這樣entries.sys.contentType.sys.id包含像字符串"ctaBlock""deviceList"

我建議使用如下地圖:

import CtaBlock from './CTABlock';
import DeviceList from './DeviceList';
import FallbackComponent from './FallbackComponent';
const keyMap = {
    ctaBlock : CtaBlock,
    deviceList : DeviceList,
    default: FallbackComponent,
};
...
componentList.map( entries => {
    const key = entries.sys.contentType.sys.id;
    const Component = keyMap[ key ] || keyMap.default;
    return <Component />;
} );

請參閱以下示例: https : //jsfiddle.net/v7do62hL/2/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM