如何将渲染功能中的Jsx分离为ES6中的单独文件?或任何其他解决方案的反应分离逻辑和演示? [英] How to Separate Jsx inside render function into a separate file in ES6? or any other solution in react to separate the Logic and presentation?

查看:198
本文介绍了如何将渲染功能中的Jsx分离为ES6中的单独文件?或任何其他解决方案的反应分离逻辑和演示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是ES5中的代码,其中jsx被写入单独的文件中。

  import反应的反应; 
从'./template.jsx'导入模板;

const DetailElement = React.createClass({
render:Template
});

导出默认DetailElement;
在此输入代码

template.jsx文件将如下

  import来自'react'的反应; 

const render = function(){

return(
< div> Hello World< / div>
);
};

导出默认渲染;

如何使用ES6类编写相同的?或者任何其他解决方案可以做这种分离?



我已经得到了这样的ES6代码

  import反应,{Component} from'react'; 
从'./template.jsx'导入模板;

export default DetailElement extends Component {
componentDidMount(){
// some code
}
};
DetailElement.prototype.render = Template;

是的,这是正常的。

解决方案

是的,你可以做到这一点,你的模板代码就像一个功能齐备的基本上是一个返回jsx的函数。您只需要在您的DetailElement类中呈现您的模板

  import从react进行反应; 
从'./template.jsx'导入模板;

class DetailElement extends React.Component {
render = Template
};

导出默认DetailElement;

这里是我创建的一个例子, codepen链接$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $

现在是一个es6类功能,您可以在class或babel变量之外定义类属性, b

Here is the code in ES5 in which the jsx is written into a separate file

import React from 'react';
import Template from './template.jsx';

const DetailElement = React.createClass({
  render: Template
});

export default DetailElement;
enter code here

template.jsx file will be like this

import React from 'react';

const render = function() {

    return (
      <div>Hello World</div>
    );
};

export default render;

How can I write the same using ES6 Classes ? Or any other solution is available to do this separation ?

I have got the ES6 code something like this

import React, {Component} from 'react';
import Template from './template.jsx';

export default DetailElement extends Component {
   componentDidMount() {
    // some code
  }
};
DetailElement.prototype.render = Template;

Yes this is working.

解决方案

Yes you can do it your template code is like a functional comoponent basically it is a function that returns jsx. You just need to render your template in your DetailElement class

import React from 'react';
import Template from './template.jsx';

class DetailElement extends React.Component{
  render = Template
};

export default DetailElement;

here is an example I created codepen link now is a es6 class feature that you can define class property outside class or babel transformer that you need to check

这篇关于如何将渲染功能中的Jsx分离为ES6中的单独文件?或任何其他解决方案的反应分离逻辑和演示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆