Render a react app in a non react web page

前端 未结 1 1052
陌清茗
陌清茗 2021-02-06 11:29

I was wondering if its possible to render an entire react app in a non react web page. I tried many links where it suggested code snippets as follows which shows to render just

相关标签:
1条回答
  • 2021-02-06 12:13

    See comments on question for more context on this answer


    index.html

    <!DOCTYPE html>
    <html>
        <head>
            <title>Example</title>
            <script type="text/javascript" src="/bundle.js"></script>
        </head>
        <body>
            <div id="content1">
            </div>
            <script type="text/javascript">
                mount("content1", "testing")
            </script>
    
            <div id="content2">
            </div>
            <script type="text/javascript">
                mount("content2", "more testing")
            </script>
        </body>
    </html>
    

    index.js

    import React from 'react'
    import { render } from 'react-dom'
    import { createStore } from 'redux'
    import { Provider } from 'react-redux'
    import { App } from './app'
    
    window.mount = function(id, customText) {
        const store = createStore((state = {}) => state)
        render(
            <Provider store={store}>
                <App text={customText} />
            </Provider>, 
            document.getElementById(id)
        )
    }
    

    app.js

    import React from 'react'
    
    export const App = ({ text }) => {
        return (
            <div>{text}</div>
        )
    }
    

    This only has redux integration in so far as it creates a store and wraps the app in a Provider, but I can't see any reason why it wont work like normal from there.

    I tested this using webpack to bundle and webpack-dev-server to serve.

    0 讨论(0)
提交回复
热议问题