[英]How to use HTML with JS in React app to export component
我正在構建MERN項目,在react
部分我得到了:
- src/
- components/
- AdminPage/
- admin-page.html
- admin-page.css
- admin-page.js
所以問題出在App.js
中:
我怎么能使用常規的 html、css、js 而不是在<AdminPage/>
組件中反應:
import React from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import HomePage from './components/HomePage/HomePage.component';
import LoginPage from '../src/components/LoginPage/LoginPage.component';
import RegisterPage from '../src/components/RegisterPage/RegisterPage.component';
import UserPage from '../src/components/UserPage/UserPage.component';
import AdminPage from '../src/components/AdminPage/AdminPage.component';
有沒有辦法不使用像AdminPage.component.jsx
這樣的經典方式並從那里導出組件; 我怎么能用常規的 html、css 和 js 做到這一點?
我假設您不想考慮功能組件,因為在 html/css/js 中維護了一些無法輕松重構為 React 的內容:
IE。
const NewComponent = () => {
const functions = () => {
}
return (
<div style={styles} ></div>
);
}
const styles = {
...css
}
export default NewComponent;
然后我會說您最好的解決方案是將 admin-page.html 中的 html 的正文粘貼到您的 index.html 文件中。
最好在根 div 標簽 ( ) 下。
這將顯示在您的所有 React 代碼下(就像頁腳一樣),但您可以使用 class 名稱或 id 在某些條件下顯示/隱藏頁面。
然后只需將您的 css 和 js 鏈接為 header 和頁腳中的單獨樣式表/腳本。
我強烈建議不要這樣做,因為它很可能會增加您對該項目的技術債務。
希望能幫助到你: )
[更新]
默認情況下,React 不允許您在組件中注入 HTML,原因包括跨站點腳本。 但是,對於 CMS 或 WYSIWYG 編輯器等某些情況,您必須處理原始 HTML。 在本指南中,您將了解如何在組件中嵌入原始 HTML。
dangerouslySetInnerHTML Prop 如果你嘗試直接在組件內渲染 HTML 字符串,React 會自動對其進行清理並將其渲染為純字符串。
好的,如果您只想添加完整的 200 多行 HTML / JS ,請再次查看此內容,我想說您可以將它們導入到帶有危險 SetHTML 屬性的組件中。 像這樣:
const HTML = import('../the/file/path/to/the.html');
const JS = import('../the/file/path/to/the.js');
const newComponent = () => {
return (
`<div dangerouslySetInnerHTML={{ __html: myHTML }} />;`
)
}
或者,如果您想要一個更安全的解決方案,您可以使用 dompurify:
如果 XSS 是主要問題,您可以使用像 DOMPurify 這樣的外部庫來清理 HTML 字符串,然后再使用 dangerouslySetInnerHTML 屬性將其注入 DOM。
要安裝 DOMPurify 庫,請運行以下命令。
npm i dompurify
您可以在下面查看示例用法。
import DOMPurify from "dompurify";
const myHTML = `<h1>John Doe</h1>`;
const mySafeHTML = DOMPurify.sanitize(myHTML);
const App = () => <div dangerouslySetInnerHTML={{ __html: mySafeHTML }} />;
您還可以將 DOMPurify 配置為僅允許特定的標簽和屬性。
// ...
const mySafeHTML = DOMPurify.sanitize(myHTML, {
ALLOWED_TAGS: ["h1", "p", "span"],
ALLOWED_ATTR: ["style"],
});
// ...
非常感謝 Gaurav Singhal 撰寫了這篇精彩的文章:
https://www.pluralsight.com/guides/how-to-use-static-html-with-react
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.