javascript - 改变 React 渲染结构的最佳方法

标签 javascript templates reactjs

我允许征求您的意见。事实上,我想到了一种改变 React 组件(DOM)结构的方法。例如,我有一个组件 Page1。通常,我们有这样的:

import React from "react";

class Page1 extends React.Component
{
    ...
    render()
    {
        return (
            /*Here JSX DOM*/
        );
    }
}

为了更改此页面的 DOM(根据模板),我认为:

import React from "react";

class Page1 extends React.Component
{
    ...
    render()
    {
        return Template.get("page1", this.props);
    }

}

Template类的get方法根据配置中定义的模板返回JSX DOM:

{
    template: "base"
}

模板类:

import {template} from "config" // Name of a template

class Template
{
    static get(componentName, props)
    {
        var templatePath = path.join("templates", template);
        return require(templatePath)[componentName](props);
    }
}

在 templates 文件夹中,我们可以有这样的结构:

templates
    |
    |____base
    |       |
    |       |__index.js
    |       |
    |       |__pag1.tpl.jsx
    |
    |____other
            |
            |__index.js
            |
            |__page1.tpl.jsx

基本模板的 page1.tpl.jsx 如下所示:

import React from "react";

export default function(props) {
   return (
      <div>Hello World !!!</div>
   );
}

我对你的意见很感兴趣。

最佳答案

在我看来, react 组件应该尽可能模块化,因此它们就像一个模板。

So, your idea is good, but you should use react components as templates instead of normal es6 classes.

React 组件可以通过定义 propTypes 自动检查(必需的)属性。此外,语法将从

return Template.get("page1", this.props);

return <Page1 {...this.props} />;

在我看来,这更容易阅读。

关于javascript - 改变 React 渲染结构的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31046100/

相关文章:

Javascript/Php - 当直接在 URL 中键入操作表单页面时重定向

c++ - std::array 的部分模板参数推导或解决方法?

javascript - 确保尽早评估某一行代码

javascript - 从 ReactJS 数组中删除 Stateful 元素

javascript - 为什么 typeof JSON.parse 返回字符串

javascript - 更改 Aloha-Editor 的语言

javascript - 从 jQuery .change 上具有相同类的不同复选框中获取唯一字段

python - 如何在 Django 中的 HTML 表单上显示表单中的多对多字段

c++ - 使用类型作为索引器

javascript - 如何以 React 方式关闭 Modal?