动态渲染来自字符串数组的反应组件

时间:2017-12-29 23:37:40

标签: javascript reactjs

在反应代码中从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! 

1 个答案:

答案 0 :(得分:1)

当我理解你的时候,想要存档的是,将字符串键映射到某个组件,对吗?

SELECT Table1.*, [Table1].[LastName] & ", " & [Table1].[FirstName] AS FullNameLastFirst FROM Table1; 包含entries.sys.contentType.sys.id"ctaBlock"等字符串?

我建议使用如下地图:

"deviceList"

查看示例: https://jsfiddle.net/v7do62hL/2/