最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Passing a value to bundled React JS file? - Stack Overflow

programmeradmin1浏览0评论

I wonder if it is possible to pass an argument to a react entry point.

My entry point looks like this:

module.exports = {
    entry: "./js/ponents/Application.js",
    output: {
        path: "./dist",
        filename: "bundle.js"
    },
    // ...
}

My Application.js:

import React from 'react';
import ReactDOM from 'react-dom';
import AnotherComponent from './AnotherComponent';

ReactDOM.render(<AnotherComponent />, document.getElementById('content'));

Not I bundle my application with webpack and include this bundle in another application. This application provides a div with id "content":

<body>
    <div id="content"></div>
    <script src="bundle.js" />
</body>

I know that I can do something like

<script src="bundle.js" myargument="somevalue" />

but how can I get this value for passing it to the react ponent AnotherComponent as a property?

I wonder if it is possible to pass an argument to a react entry point.

My entry point looks like this:

module.exports = {
    entry: "./js/ponents/Application.js",
    output: {
        path: "./dist",
        filename: "bundle.js"
    },
    // ...
}

My Application.js:

import React from 'react';
import ReactDOM from 'react-dom';
import AnotherComponent from './AnotherComponent';

ReactDOM.render(<AnotherComponent />, document.getElementById('content'));

Not I bundle my application with webpack and include this bundle in another application. This application provides a div with id "content":

<body>
    <div id="content"></div>
    <script src="bundle.js" />
</body>

I know that I can do something like

<script src="bundle.js" myargument="somevalue" />

but how can I get this value for passing it to the react ponent AnotherComponent as a property?

Share Improve this question asked Nov 10, 2016 at 7:00 RiaRia 2,1004 gold badges16 silver badges21 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

What about

<script id="bundle" src="bundle.js" myargument="somevalue" />

and then

const myScript = document.getElementById('bundle');

ReactDOM.render(<AnotherComponent 
   myArgument = {myScript.getAttribute('myargument')}
/>, document.getElementById('content')

);

In ReactJS file src/index.js

import React from 'react';
import ReactDOM from 'react-dom';

window.MyReactApp = {
    init: (selector, myData) => {
        selector = selector.substring(1);
        const renderComponent = (<homeComponent mydata={myData} />);
        ReactDOM.render(renderComponent, document.getElementById(selector));
    },
};

Now load the ReactJs App where you want to load.

<script type="text/javascript" src="bundle.min.js"></script>
<div id="load-myreactapp"></div>

<script type="text/javascript">
    const myData = {};
    MyReactApp.init('#load-myreactapp', myData);
</script>
发布评论

评论列表(0)

  1. 暂无评论