json - 从 JSON 渲染 React Native 元素

标签 json reactjs react-native

我四处搜索...找不到我要找的东西,所以我感谢任何帮助!这就是我想要的:

我正在为 React Native 应用程序构建类似 CMS 的设置。这样应用程序的管理员就可以登录 CMS 仪表板,并更新应用程序的页面/ View ,而无需进入硬编码。我希望他们能够从预设的组件列表中进行选择,并能够按照他们想要的任何顺序将它们拖放到应用程序中,并且能够更新内容和颜色等。让我举个例子...

我想象有一个主页,顶部有一个旋转横幅,然后是一个信息模式按钮,然后是一组转到子页面的菜单链接。

所以我认为,从开发角度来看,是为应用程序管理员提供所见即所得类型的设置,并将其结果存储在数据库中。它可以在数据库中存储为:

<RotatingBanner />
<Modal />
<ContentMenu>
    <ContentMenuLink title="About" />
    <ContentMenuLink title="Competitive" />
    <ContentMenuLink title="Recreational" />
    <ContentMenuLink title="Tournaments" />
<ContentMenu />

现在,当我尝试将其渲染到屏幕上时,我会继续将其渲染为实际单词与它们所代表的组件(如果有意义的话)。因此页面看起来就像上面的代码块,而不是看到旋转的横幅和模式等。

我尝试过一个工具将 HTML 转换为 React Native 元素...有谁知道如何转换获取的 JSON,如下所示:

{content: "<RotatingBanner /><Modal /><ContentMenu>...."}

并让它在渲染函数中创建真正的组件吗?如果您愿意,我们将不胜感激关于创建此类 CMS 的任何其他想法或想法/建议。

谢谢!

最佳答案

假设您有以下 JSON:

const data = {
  "components": [
    {"name": "component1", props: {"hello": "world"}},
    {"name": "component2", props: {"color": "red"}},
  ]
}

制作组件,然后在对象( map )中引用它们:

import Component1 from './Component1'
import Component2 from './Component2'

const COMPONENT_MAP = {
  component1: Component1,
  component2: Component2,
}

然后制作你的包装组件:

const Wrapper = ({data}) => (
  <View>
    {data.components.map(({name, props}) => {
      const Component = COMPONENT_MAP[name]
      return <Component {...props} />
    }}
  </View>
)

瞧:)

<Wrapper data={data} />

关于json - 从 JSON 渲染 React Native 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42893192/

相关文章:

javascript - 如何使用 JSON 在 angularjs 中创建双向绑定(bind)?

json - Gradle : How to use task's output file data in another task?

javascript - 提交按钮重新加载页面

javascript - Redux-Saga 调用不工作

javascript - 将 JSON 响应中的值存储到 AsyncStorage React Native

javascript - 函数/对象字面量之前的问号意味着

javascript - 如何使用 Node.js 中包含空格的 JSON 键获取 JSON 对象值

json - 如何在 SSDT 中架构绑定(bind)使用地理或 Json 的函数?

reactjs - React Formik 给出 Cannot read properties of undefined (reading 'fullName') 错误

ios - 如何设置关联域/通用链接