2017-09-01 119 views
3

如果我想使用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); 
+0

我只想用'if(document.getElementById('Clock')){/ *激活反應組件* /}' –

+0

感謝您的輸入。 但是,使用這種方法是否正確,因爲應用程序可以增長很多? – MrGilbertMan

+0

不,這絕對不是一個推薦的做法,但唯一真正的缺點是捆綁包的大小和ifs的數量不斷增加。更好的方法是使用webpack捆綁應用程序的不同部分,並只將它們加載到每個不同的頁面中 –

回答

2

<div id="Clock" data-react="Clock"></div> 
<div id="HelloWorld" data-react="HelloWorld"></div> 

的例子,我會看到兩種方式提高質量和難度的。在這兩種情況下,您都使用良好的舊錨點元素將頁面重定向到不同模板對應的url。

  • 手動檢查的div的ID的

在這種情況下,每個模板包括含有在該應用中,並與對應於該特定部件的ID的單個元件都相同的javascript束的存在。這個想法是檢查頁面中是否存在元素,如果是,則激活其相應的反應組件。

if (document.getElementById('component-root')) { 
    ReactDOM.render(<Component />, document.getElementById('component-root')); 
} 

另一方面,它很容易實現。不利的一面是,這個捆綁包總是會變得越來越大,而且每當你添加一個新的「頁面」時,ifs的列表就會增加。

  • 獨立的模塊,在實際束

不同的束經理存在,但我建議你使用的WebPack創建包含應用程序的唯一特定部分多束。然後,每個模板只包含相應的div元素,以及該特定的包。


<head><script src="/js/clock.js"></head> 
<body><div id="root-clock"></div></body> 

<head><script src="/js/otherComponent.js"></head> 
<body><div id="root-other-component"></div></body> 

如何打包多個捆綁帶的WebPack是出於這個答案的範圍,但看here

1

我試着做一個沒有路由器的反應應用程序。我使用三元運算符從組件切換到組件。

// App Component 
class App extends Component { 
    constructor(props) { 
    super(props) 

    this.state = { 
     inClockComponent: true, 
     inHelloWorldComponent: false, 
     inOtherComponent: false 
    } 

    } 


render() { 
    const {inClockComponent, inHelloWorldComponent, inOtherComponent} = this.state 
    return (
     <div> 
     { 

     inClockComponent 
     ? <Clock> : inHelloWorldComponent 
      ? <HelloWorld> : inOtherComponent ? <OtherComponent> : 
       <div>No Component Here</div> 

     } 
    </div> 
    } 

你可以通過從App組件的功能,將所述顯示狀態更改爲App

每個子組件實施例

// in App Component 
showHelloWorldComponent() { 
    this.setState({ 
     inClockComponent: false, 
     inHelloWorldComponent: true, 
     inOtherComponent: false 
    )} 
} 

您插入功能到將導航到不同組件的按鈕

// in Clock Component 

render() { 
    return (
    <div> 
     <h2>Time is 5:15 P.M.</h2> 
     <button onClick={this.props.showHelloWorldComponent}> 
     Go To Hello World 
     </button> 
) 
} 

這是一個混亂的解決方案,並在一個大的應用程序使用它,我不會建議,但我希望這回答您的問題!

相關問題