简体   繁体   English

从旧版JS渲染React应用的解决方案

[英]Solution for rendering React app from legacy JS

For example I have ReactApp which is packed via Webpack : 例如我有ReactApp通过Webpack

import React from 'react'
import ReactDom from 'react-dom';
import {Provider} from 'react-redux'
import {createStore, applyMiddleware} from 'redux'
import thunk from 'redux-thunk'

import rootReducer from '../reducers/index';

let store = createStore(
    rootReducer,
    {},
    composeWithDevTools(
        applyMiddleware(thunk)
    )
)

ReactDom.render(
    <Provider store={store}>
        <div>
            TEST IF WORKS
        </div>
    </Provider>,
    document.getElementById('root-element')
)

And I would like to call it from legacy JS function, which is available in global scope, something like: 我想从旧版JS函数(在全局范围内可用)中调用它,例如:

<script type="text/javascript">
function drawReactApp(el, initialData) {
    // Render ReactApp on dynamic HTML element ID
}
</script>

The problem is that: 问题是:

1) I need to render multiple ReactApp's using drawReactApp() (render widgets). 1)我需要使用drawReactApp() (渲染小部件)来渲染多个ReactApp。

2) I can't find solution for rendering ReactApp using legacy JS code, because I can't include React JS scripts, only bundle file (this is limitation). 2)我找不到使用旧版JS代码渲染ReactApp的解决方案,因为我无法包括React JS脚本,只能包含捆绑文件(这是限制)。

3) I can render ReactApp on "hardcoded" HTML ID element (for example: "#root-element"), but can't make ID dynamic (only legacy JS can know on which element ReactApp should be rendered) 3)我可以在“硬编码” HTML ID元素(例如:“#root-element”)上呈现ReactApp,但不能使ID动态化(只有旧版JS才能知道应在哪个元素上呈现ReactApp)

Is there any advice or solutions on this? 有什么建议或解决方案吗?

Thank you! 谢谢!

In your «ReactApp», you could create a global function to render it: 在«ReactApp»中,您可以创建一个全局函数来呈现它:

window.drawThisReactApp = (into, initialData) => {
  ReactDOM.render(<Provider ...><ReactApp {...initialData} /></Provider>, into);
}

Then, in "legacy" JS: 然后,在“旧版” JS中:

<script>
  window.drawThisReactApp(document.getElementById(...), {...});
</script>

NB No reference to React or ReactDOM needed here. 注意:此处无需引用ReactReactDOM

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM