如何从React组件中的另一个文件呈现HTML

如何从React组件中的另一个文件呈现HTML

本文介绍了如何从React组件中的另一个文件呈现HTML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从React组件中的另一个文件呈现HTML?

Is it possible to render HTML from another file in a React component?

我尝试过以下操作,但它不起作用:

I have tried the following, but it does not work:

var React = require('react');

/* Template html */
var template = require('./template');

module.exports = React.createClass({
    render: function() {
        return(
            <template/>
        );
    }
});


推荐答案

如果你的 template.html 文件只是HTML而不是React组件,那么你就不能像使用JS文件那样需要它了。

If your template.html file is just HTML and not a React component, then you can't require it in the same way you would do with a JS file.

但是,如果您使用的是Browserify,则会有一个名为的转换,这将允许您要求非js文件为字符串。添加转换后,您将能够要求HTML文件并将它们导出为只是字符串。

However, if you are using Browserify — there is a transform called stringify which will allow you to require non-js files as strings. Once you have added the transform, you will be able to require HTML files and they will export as though they were just strings.

一旦您需要HTML文件,必须使用。

Once you have required the HTML file, you'll have to inject the HTML string into your component, using the dangerouslySetInnerHTML prop.

var __html = require('./template.html');
var template = { __html: __html };

React.module.exports = React.createClass({
  render: function() {
    return(
      <div dangerouslySetInnerHTML={template} />
    );
  }
});

这与React的很多相反。将模板创建为使用JSX的React组件而不是常规HTML文件会更自然。

This goes against a lot of what React is about though. It would be more natural to create your templates as React components with JSX, rather than as regular HTML files.

JSX语法使得表达结构化数据非常容易,例如HTML,特别是当您使用。

The JSX syntax makes it trivially easy to express structured data, like HTML, especially when you use stateless function components.

如果您的 template.html 文件看起来像这样

If your template.html file looked something like this

<div class='foo'>
  <h1>Hello</h1>
  <p>Some paragraph text</p>
  <button>Click</button>
</div>

然后你可以把它转换成一个看起来像这样的JSX文件。

Then you could convert it instead to a JSX file that looked like this.

module.exports = function(props) {
  return (
    <div className='foo'>
      <h1>Hello</h1>
      <p>Some paragraph text</p>
      <button>Click</button>
    </div>
  );
};

然后你可以要求并使用它而不需要字符串化。

Then you can require and use it without needing stringify.

var Template = require('./template');

module.exports = React.createClass({
  render: function() {
    var bar = 'baz';
    return(
      <Template foo={bar}/>
    );
  }
});

它维护原始文件的所有结构,但利用了React的道具模型的灵活性并允许用于编译时语法检查,与常规HTML文件不同。

It maintains all of the structure of the original file, but leverages the flexibility of React's props model and allows for compile time syntax checking, unlike a regular HTML file.

这篇关于如何从React组件中的另一个文件呈现HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 08:33