React:如何加载和呈现外部 html 文件? [英] React: how to load and render external html file?

查看:17
本文介绍了React:如何加载和呈现外部 html 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 React 和 Redux 构建了一个小型博客应用程序.博客显示带有标题、作者、标签和帖子描述的帖子页面.当单击标题或阅读更多"按钮时,我想从本地项目的数据文件夹中加载并呈现一个带有相应帖子的 HTML 文件,其中包含所有帖子.

Redux 正在管理博客的状态,加载包含 8 个不同帖子的初始 posts.json 文件,包括数据文件夹中相应 html 文件的 htmlPath.

解决方案

在我看来,您在这里有两个问题需要解决.第一个是如何在 React 中设置元素的 innerHTML.另一个是如何根据给定的变量(例如当前路线、文本字段的输入等)获取要呈现的特定 HTML.

1.设置元素的innerHTML

您可以使用 dangerouslySetInnerHTML 道具执行此操作.顾名思义,它将上述元素的 innerHTML 设置为您指定的任何内容......是准确的,因为它旨在让您在使用此功能之前三思而后行.

官方文档 内容如下:

<块引用>

对innerHTML 的不当使用会使您面临跨站点脚本(XSS) 攻击.众所周知,清理用于显示的用户输入很容易出错,而未能正确清理是导致互联网上出现网络漏洞的主要原因之一.

查看此演示或下面的代码片段.

var Demo = React.createClass({getInitialState:函数(){返回 {showExternalHTML: false};},渲染:函数(){返回 (<div><button onClick={this.toggleExternalHTML}>Toggle Html</button>{this.state.showExternalHTML ?<div><div risklySetInnerHTML={this.createMarkup()} ></div>

: 空值}

);},切换外部HTML:函数(){this.setState({showExternalHTML: !this.state.showExternalHTML});},创建标记:函数(){return {__html: '<div class="ext">Hello!</div>'};}});ReactDOM.render(<演示/>,document.getElementById('容器'));

.ext {边距顶部:20px;宽度:100%;高度:100px;背景:绿色;白颜色;字体大小:40px;文本对齐:居中;行高:100px;}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><div id="container"></div>


2.从外部源获取 HTML

请注意,上面的示例实际上并没有从外部文件中获取 HTML,而是直接以字符串形式输入.

动态获取选择特定文件的一种简单方法是让您的后端(例如 php)从本地文件夹读取文件,解析文本,然后通过 AJAX 请求将其发送回.

示例

//你的 React 组件fetchExternalHTML:函数(文件名){Ajax.getJSON('/myAPI/getExternalHTML/' + fileName).then(响应 =>{this.setState({extHTML:响应});}, 错误 =>{//在这里处理你的错误});}

I building a small blog app using React and Redux. The blog show Posts page with title, author, tags and description of a post. When clicking on title or "read more" button, I want to load and render an HTML file with corresponding post from a local project's data folder with all the posts.

Redux is managing the state of the blog, loading initial posts.json file with 8 different posts, including htmlPath for the corresponding html file in the data folder.

解决方案

The way I see it is that you have 2 problems to solve here. The first is how to set the innerHTML of an element in React. The other is how to get a specific HTML to render depending on a given variable (e.g the current route, the input of a textfield, etc).

1. Setting the innerHTML of an element

You can do this with the dangerouslySetInnerHTML prop. As the name suggests it sets the innerHTML of the said element to whatever you specify... and yes, the "dangerously" is accurate as it's intended to make you think twice before using this feature.

The Official Documentation reads as follows:

Improper use of the innerHTML can open you up to a cross-site scripting (XSS) attack. Sanitizing user input for display is notoriously error-prone, and failure to properly sanitize is one of the leading causes of web vulnerabilities on the internet.

Check out this Demo or the snippet below.

var Demo = React.createClass({

  getInitialState: function() {
    return {showExternalHTML: false};
  },
  
  render: function() {
    return (
      <div>
        <button onClick={this.toggleExternalHTML}>Toggle Html</button>
        {this.state.showExternalHTML ? <div>
          <div dangerouslySetInnerHTML={this.createMarkup()} ></div>
        </div> : null}
      </div>
    );
  },
  
  toggleExternalHTML: function() {
    this.setState({showExternalHTML: !this.state.showExternalHTML});
  },
  
  createMarkup: function() { 
    return {__html: '<div class="ext">Hello!</div>'};
  }

});

ReactDOM.render(
  <Demo />,
  document.getElementById('container')
);

.ext {
  margin-top: 20px;
  width: 100%;
  height: 100px;
  background: green;
  color: white;
  font-size: 40px;
  text-align: center;
  line-height: 100px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>


2. Fetching the HTML from an external source

Note that the above example does not actually get the HTML from an external file, but is entered directly as a string.

One simple way to do dynamically fetch a choose a specific file would be to let your backend (e.g php) read the file from a local folder, parse the text, and send it back through an AJAX request.

Example

//Your React component
fetchExternalHTML: function(fileName) {
  Ajax.getJSON('/myAPI/getExternalHTML/' + fileName).then(
    response => {
      this.setState({
        extHTML: response
      });
    }, err => {
      //handle your error here
    }
  );
}

这篇关于React:如何加载和呈现外部 html 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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