我允许征求您的意见。事实上,我想到了一种改变 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/