简体   繁体   English

更改React渲染结构的最佳方法

[英]Best way to change React render structure

I allow to request your opinion. 我允许要求您的意见。 In fact, I think of a way to change the structure of a react component (The DOM). 实际上,我想到了一种改变反应组件(DOM)结构的方法。 For example, I have a component Page1 . 例如,我有一个组件Page1 Normaly, we have this: 通常,我们有:

import React from "react";

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

For change the DOM of this page (according a template), I think this: 为了更改此页面的DOM(根据模板),我认为是这样的:

import React from "react";

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

}

The get method of Template class return the JSX DOM according the template define in config: Template类的get方法根据config中定义的模板返回JSX DOM:

{
    template: "base"
}

The Template class: 模板类:

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);
    }
}

In templates folder, we can have this structure: 在模板文件夹中,我们可以具有以下结构:

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

And the page1.tpl.jsx to base template look like this: 基本模板的page1.tpl.jsx如下所示:

import React from "react";

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

I 'm interested in you opinion. 我对您的意见感兴趣。

In my opinion react components should be as modular as possible, so they will be like an template. 我认为React组件应该尽可能地模块化,因此它们就像模板一样。

So, your idea is good, but you should use react components as templates instead of normal es6 classes. 因此,您的想法很好,但是您应该使用react组件作为模板,而不是常规的es6类。

React components can check the (required) properties automatically be defining propTypes . React组件可以通过定义propTypes自动检查(必需)属性。 Additionally, the syntax will be change from 此外,语法将从

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

to

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

Wich, in my opinion, is easier to read. 我认为,威奇更容易阅读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM