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

时间:2021-12-22 04:21:41

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

4 个解决方案

#1


31  

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.

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

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.

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

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

一旦需要HTML文件,就必须使用dangerouslySetInnerHTML prop将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.html file 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.

然后你可以要求并使用它而不需要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文件不同。

#2


4  

You can use the dangerouslySetInnerHTML property 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>'

#3


1  

You could do it if template is a react component.

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

Template.js

var React = require('react');

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

module.exports = Template;

MainComponent.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 Components,则不需要正常输入。

#4


0  

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

通常只有从道具渲染的组件。喜欢这个:

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.

然后在您拥有逻辑的上层组件中,您只需导入Template组件并传递所需的道具。您的所有逻辑都保留在更高级别的组件中,而模板只会呈现。这是在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的标记。

#1


31  

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.

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

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.

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

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

一旦需要HTML文件,就必须使用dangerouslySetInnerHTML prop将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.html file 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.

然后你可以要求并使用它而不需要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文件不同。

#2


4  

You can use the dangerouslySetInnerHTML property 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>'

#3


1  

You could do it if template is a react component.

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

Template.js

var React = require('react');

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

module.exports = Template;

MainComponent.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 Components,则不需要正常输入。

#4


0  

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

通常只有从道具渲染的组件。喜欢这个:

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.

然后在您拥有逻辑的上层组件中,您只需导入Template组件并传递所需的道具。您的所有逻辑都保留在更高级别的组件中,而模板只会呈现。这是在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的标记。