![](/img/trans.png)
[英]How do I manage CSS framework to use only one component in my React App
[英]How to add/use React component in only one part (cart page) of my existing node project?
到目前為止,我一直在使用create-react-app
來構建 React 應用程序和組件。
但是,我有一個正在處理的項目,它是使用純 JS 構建在節點中進行 Dom 操作的,我想只對一個頁面(購物車頁面)添加反應。
我看過的所有教程都假設您是從頭開始項目,我似乎無法弄清楚如何將 React 添加到我項目的單個部分中。
有人可以指出我正確的方向嗎?
我建議你從這里開始: https ://reactjs.org/docs/rendering-elements.html
React Docs 實際上也指向本教程的非“create-react-app”教程: https ://blog.usejournal.com/creating-a-react-app-from-scratch-f3c693b84658
這是用於渲染元素的 React Docs。 TLDR 版本:
在您希望 React 組件所在的 HTML 文件中,創建一個空 div 並為其指定一個唯一名稱(即“app”或“react-component”)
然后創建您的組件等,並讓 ReactDOM 在唯一的 id 名稱上呈現。
為了讓它渲染,在你的節點應用程序中,將它指向構建路徑,通常是 bundle.js
我已經完成了這項工作,並設法將 React 組件(用 JSX 編寫)用於我的自定義 JavaScript 應用程序(通過 Webpack 捆綁)的特定部分。 你基本上需要三樣東西。
1) 您的自定義 JavaScript 應用
// MyApp.js
import { renderMyReactComponent } from "./MyReactComponent.jsx";
class MyApp {
// Call this when you want to show your React component
showMyReactComponent() {
// Create an empty div and append it to the DOM
const domElem = document.createElement("div");
domElem.classList.add("my-react-component");
document.append(domElem);
// Render your React component into the div
renderMyReactComponent(domElem);
}
}
2.) 你的 React 組件
// MyReactComponent.jsx
import React from "react";
import ReactDOM from "react-dom";
class MyReactComponent extends React.Component {
render() {
// JSX, woah!
return <h2>My React Component</h2>
}
}
// A way to render your React component into a specific DOM element
export const renderMyReactComponent = (domElem) => {
// NB: This syntax works for React 16.
// React 18 requires a slightly different syntax.
ReactDOM.render(
<MyReactComponent />,
domElem
);
}
3.) 一種解析 jsx 文件並構建應用程序的方法
我使用 Webpack 並根據這篇文章修改了我現有的 Webpack 配置: https ://medium.com/@JedaiSaboteur/creating-a-react-app-from-scratch-f3c693b84658(React 官方文檔也指向本教程)
有用的文章
這篇來自官方 React 文檔的文章很好讀: https ://reactjs.org/docs/add-react-to-a-website.html。 這也解釋了使用腳本標簽而不是 Webpack 將 React 組件集成到現有 JavaScript 應用程序的不同方法。
您可能也對與您的類似問題的答案感興趣。
正如@pinkwaffles 在他們的回答中指出的那樣,以下文章有助於理解將 React 組件渲染為 DOM 元素: https ://reactjs.org/docs/rendering-elements.html
PS:請注意,在撰寫此答案時,上述文章已經使用 React 18 作為示例,而我上面的示例仍然使用 React 16; 所以關於ReactDOM
的語法有點不同。 但想法是一樣的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.