如果我想使用reactjs製作不是單個頁面的Web應用程序。 我應該將所有反應代碼編譯成單個文件並將其加載到應用程序的所有頁面上,然後使用我公開的函數來渲染必要的組件?在沒有路由器組件的情況下使用反應
例如HTML文件index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Clock from './Clock';
import HelloWorld from './HelloWorld';
import OtherComponent from './OtherComponent';
const APPS = {
Clock,
HelloWorld,
OtherComponent
};
const MyReactRender = react => {
let component = react.getAttribute('data-react');
let App = APPS[component];
if(App != undefined) {
ReactDOM.render(<App />, document.getElementById(component));
}
}
document.querySelectorAll('[data-react]').forEach(MyReactRender);
我只想用'if(document.getElementById('Clock')){/ *激活反應組件* /}' –
感謝您的輸入。 但是,使用這種方法是否正確,因爲應用程序可以增長很多? – MrGilbertMan
不,這絕對不是一個推薦的做法,但唯一真正的缺點是捆綁包的大小和ifs的數量不斷增加。更好的方法是使用webpack捆綁應用程序的不同部分,並只將它們加載到每個不同的頁面中 –