gpt4 book ai didi

javascript - 从字符串数组动态渲染 react 组件

转载 作者:太空宇宙 更新时间:2023-11-04 15:26:18 25 4
gpt4 key购买 nike

在 React 代码中从 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" 这样的字符串?

我建议使用 map ,如下所示:

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/

关于javascript - 从字符串数组动态渲染 react 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48029569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com