在 React 中将模板分离到外部文件 [英] Separate templates to external file in React

查看:47
本文介绍了在 React 中将模板分离到外部文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为客户开发 ReactJS 应用程序.我希望客户端能够自定义应用程序中的一些配置和模板.所以我创建了一个 config.js 文件

window.APP_CONFIG = {网址:'example.com',模板: {物品: '<div><h3>一个新的项目标题</h3>{ 商品描述 }

'}};

如何在我的 React 应用中使用这个变量?我尝试了以下操作,但它给了我错误.

var app = React.createClass({使成为(){返回 (<div>{APP_CONFIG.template.item}

)}})

有人做过类似的事情吗?

解决方案

您并不孤单.React 模板 允许您使用 react 而不必内联jsx.

react-templates 语法与 jsx 非常相似,但允许您将组件 html 代码放在单独的 .rt 文件中 - 更简洁.RT 文件对循环和分支有更好的支持.额外的好处是,您不必绕着class"和for"等保留属性名称跳舞,还有其他优点.

来自文档:

<块引用>

为什么不使用 JSX?

有些人喜欢 JSX,有些人不喜欢.我们没有.更具体地说,在我们看来JSX 只适合 HTML 很少的组件里面.这可以通过在代码中创建 DOM 元素来实现.此外,我们喜欢将代码和 HTML 分开,因为这样感觉很对.

到目前为止我看到的主要问题是像 onMouseDown={someJsExpr} 这样的属性值在 jsx 中被神奇地引用了,但是在 react-templates 中你必须明确地引用它们作为 la onMouseDown="{someJsExpr}",没有魔法.我发现找到这样的案例并转换过来并不难.

I am working on a ReactJS app for a client. I want the client to be able to customize some of the configurations and templates in the app. So I have created a config.js file

window.APP_CONFIG = {
    url: 'example.com',
    template: {
        item: '
            <div>
                <h3>A new item title</h3>
                { item.description }
            </div>
        '       
    }
};

How can I use this variable in my react app? I have tried the following but it gives me errors.

var app = React.createClass({

  render(){
     return (
       <div>
         {APP_CONFIG.template.item}
       </div>
     )
  }
})

Anyone has done something similar?

解决方案

You are not alone. React Templates allows you to use react without having to put up with inline jsx.

The react-templates syntax is very very similar to jsx but allows you to have your component html code in a separate .rt file - much cleaner. RT files have better support for looping and branching. Added bonus, you do not have to dance around reserved attribute names like "class" and "for" and there are other advantages.

From the docs:

Why not use JSX?

Some love JSX, some don't. We don't. More specifically, it seems to us that JSX is only a good fit for components with very little HTML inside. And this can be accomplished by creating DOM elements in code. Also, we like to separate code and HTML because it just feels right.

The main gotcha I've seen so far is that attribute values like onMouseDown={someJsExpr} are magically quoted in jsx but in react-templates you have to explicitly quote them a la onMouseDown="{someJsExpr}", no magic. I found that it was not hard to find cases of this and convert them over.

这篇关于在 React 中将模板分离到外部文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆