Javascript 如何从 React 组件中的另一个文件渲染 HTML?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33973757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:44:28  来源:igfitidea点击:

How can I render HTML from another file in a React component?

javascriptreactjs

提问by Emir Marques

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

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

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

回答by Dan Prince

If your template.htmlfile 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.

如果您的template.html文件只是 HTML 而不是 React 组件,那么您就不能像处理 JS 文件那样需要它。

However, if you are using Browserify — there is a transform called stringifywhich 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.

但是,如果您使用 Browserify — 有一个名为stringify的转换,它允许您将非 js 文件作为字符串。添加转换后,您将能够要求 HTML 文件,并且它们将导出,就好像它们只是字符串一样。

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

一旦您需要 HTML 文件,您就必须使用dangerouslySetInnerHTMLprop将 HTML 字符串注入到您的组件中。

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

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

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.

不过,这与 React 的很多内容背道而驰。使用 JSX 将模板创建为 React 组件而不是常规的 HTML 文件会更自然。

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

JSX 语法使表达结构化数据(如 HTML)变得非常容易,尤其是当您使用无状态函数组件时

If your template.htmlfile looked something like this

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

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

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

然后,您可以将其转换为如下所示的 JSX 文件。

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

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 的 props 模型的灵活性并允许编译时语法检查,这与常规 HTML 文件不同。

回答by Jon Surrell

You can use the dangerouslySetInnerHTMLproperty to inject arbitrary HTML:

您可以使用该dangerouslySetInnerHTML属性来注入任意 HTML:

// Assume from another require()'ed module:
var html = '<h1>Hello, world!</h1>'

var MyComponent = React.createClass({
  render: function() {
    return React.createElement("h1", {dangerouslySetInnerHTML: {__html: html}})
  }
})

ReactDOM.render(React.createElement(MyComponent), document.getElementById('app'))
<script src="https://fb.me/react-0.14.3.min.js"></script>
<script src="https://fb.me/react-dom-0.14.3.min.js"></script>
<div id="app"></div>

You could even componentize this template behavior (untested):

您甚至可以将此模板行为组件化(未经测试):

class TemplateComponent extends React.Component {
  constructor(props) {
    super(props)
    this.html = require(props.template)
  }

  render() {
    return <div dangerouslySetInnerHTML={{__html: this.html}}/>
  }

}

TemplateComponent.propTypes = {
  template: React.PropTypes.string.isRequired
}

// use like
<TemplateComponent template='./template.html'/>

And with this, template.html(in the same directory) looks something like (again, untested):

有了这个,template.html(在同一目录中)看起来像(再次,未经测试):

// ./template.html
module.exports = '<h1>Hello, world!</h1>'

回答by Allan

You could do it if template is a react component.

如果模板是一个反应组件,你可以这样做。

Template.js

模板.js

var React = require('react');

var Template = React.createClass({
    render: function(){
        return (<div>Mi HTML</div>);
    }
});

module.exports = Template;

MainComponent.js

主组件.js

var React = require('react');
var ReactDOM = require('react-dom');
var injectTapEventPlugin = require("react-tap-event-plugin");
var Template = require('./Template');

//Needed for React Developer Tools
window.React = React;

//Needed for onTouchTap
//Can go away when react 1.0 release
//Check this repo:
//https://github.com/zilverline/react-tap-event-plugin
injectTapEventPlugin();

var MainComponent = React.createClass({
    render: function() {
        return(
            <Template/>
        );
    }
});

// Render the main app react component into the app div.
// For more details see: https://facebook.github.io/react/docs/top-level-api.html#react.render
ReactDOM.render(
  <MainComponent />,
  document.getElementById('app')
 );

And if you are using Material-UI, for compatibility use Material-UI Components, no normal inputs.

如果您使用的是 Material-UI,为了兼容性,请使用 Material-UI 组件,没有正常输入。

回答by Ivan

It is common to have components that are only rendering from props. Like this:

拥有仅从 props 渲染的组件是很常见的。像这样:

class Template extends React.Component{
  render (){
    return <div>this.props.something</div>
  }
}

Then in your upper level component where you have the logic you just import the Template component and pass the needed props. All your logic stays in the higher level component, and the Template only renders. This is a possible way to achieve 'templates' like in Angular.

然后在您拥有逻辑的上层组件中,您只需导入模板组件并传递所需的道具。您的所有逻辑都保留在更高级别的组件中,并且模板仅呈现。这是在 Angular 中实现“模板”的一种可能方法。

There is no way to have .jsx file with jsx only and use it in React because jsx is not really html but markup for a virtual DOM, which React manages.

没有办法让 .jsx 文件只包含 jsx 并在 React 中使用它,因为 jsx 不是真正的 html,而是 React 管理的虚拟 DOM 的标记。