javascript - React 访问index.html 中的组件

标签 javascript reactjs

这似乎很容易,但我完全困惑。

我开发了带有组件的 react 应用程序。现在在我的 index.html 中我有工作示例:

 <div class="container">
        <div id="app-content">

        <!-- React will render in div#app-content, works fine! -->
                    <script src="build/main.bundle.js"></script>        </div>  </div>

项目目录:

enter image description here

我想从浏览器访问组件 react 组件应用程序 java脚本,以在现有项目中实现此应用程序,例如:

<div class="container">
    <div id="component">
        <script>
            // how can i call App component to render 
            // in div#components from here
        </script>
    </div>
</div>

文件build/main.bundle.js是使用webpack生成的, 我有以下文件: webpack.config.js:

var webpack = require("webpack");

module.exports = {
/* This is the default setting for webpack */
target: "web",
/* Generate source-maps for browser side debugging */
devtool: "source-map",
/* Entry file to start building from. This is where you will want to start
 * your project.  If you wanted to build multiple entry points you could 
 * list them below.
 */
entry: {
    main: "./src/main"
},
/* Defines where to output the final built files. The [name] definition
 * is based off of the entry point's name. This example will generate
 * a main.bundle.js in the public/build directory.
 */
output: {
    path: "./public/build",
    filename: "[name].bundle.js"
},
resolve: {
    /* Defines where it can load modules from. Since we've installed our 
     * JS dependencies through npm, it can look in the node_modules
     * directory. If you use bower, you can add 'bower_components'
     * to the list.
     */
    modulesDirectories: ['node_modules'],
    /* List extensions to load in require() statements. The '' entry
     * is needed to allow you to require src/main.jsx as require('src/main.jsx')
     */
    extensions: ['', '.js', '.jsx']
},

/* Defines what modules to use */
module: {
    /* Loaders are how webpack compiles and builds the JSX extensions */
    loaders: [
        /* Any file with a .jsx extension will go through the jsx-loader */
        { test: /\.jsx$/, loader: "jsx-loader?harmony" }

        //add loader 
        // { test: /\.jsx$/, loader: ""}
    ]
},
//uncoment to use compression

// plugins: [
//     new webpack.optimize.UglifyJsPlugin({
//         compress: {
//             warnings: false
//         }
//     }),

// ]
};

ma​​in.jsx:

    var React = require('react');
    var App = require('./components/App');

    if(typeof document !== "undefined")
    {
       React.render(<App />, document.getElementById("app-content"));
    }

App.jsx:

var React = require('react');
var LineChart = require('./LineChart');
var HelloWorld = require('./HelloWorld');

var chartOptions = { responsive: true };


var dataBar = {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [
        {
            label: "My First dataset",
            fillColor: "rgba(220,220,220,0.5)",
            strokeColor: "rgba(220,220,220,0.8)",
            highlightFill: "rgba(220,220,220,0.75)",
            highlightStroke: "rgba(220,220,220,1)",
            data: [65, 59, 80, 81, 56, 55, 40]
        },
        {
            label: "My Second dataset",
            fillColor: "rgba(151,187,205,0.5)",
            strokeColor: "rgba(151,187,205,0.8)",
            highlightFill: "rgba(151,187,205,0.75)",
            highlightStroke: "rgba(151,187,205,1)",
            data: [28, 48, 40, 19, 86, 27, 90]
        }
    ]
};
var dataLine = {
    labels: ["Viens", "Divi", "Tris", "Cetri", "Pieci", "Sesi", "Septini"],
    datasets: [
        {
            label: "My First dataset",
            data: [65, 59, 80, 81, 56, 55, 40, 88]
        },
        {
            label: "My Second dataset",
            data: [28, 48, 40, 19, 86, 27, 90, 98]
        }
    ]
};

var dataLine2 = {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [
        {
            label: "My First dataset",
            data: [11, 15, 20, 25, 30, 40,70]
        },
        {
            label: "My Second dataset",
            data: [80, 50, 49, 10, 20, 35, 55, 44]
        },
        {
            label: "My Third dataset",
            data: [102, 50, 80, 65, 25,80, 90]
        },
        {
            label: "My 4 dataset",
            data: [150, 50, 50, 50, 50, 70, 89]
        },
        {
            label: "My 5 dataset",
            data: [80, 20, 50, 78, 65, 45, 100]
        },
        {
            label: "My 6 dataset",
            data: [100, 90, 80, 70, 60, 50, 40]
        },
        {
            label: "My 7 dataset",
            data: [55,66,77,88,99,100,44]
        },
    ]
};

var data = {
    startDate: "13/01/2015",
    endDate: "30/04/2015",
    title: 'LineChartDemo',
    chartData: dataLine
};

var data2 = {
    startDate: "13/01/2015",
    endDate: "30/04/2015",
    title: 'LineChartDemo',
    chartData: dataLine2
};

var App = React.createClass({
    render: function(){
        return (
            <div id="app">
                <HelloWorld name="Rolands Usāns" />
                <LineChart data={data} imageExport={['png, jpeg']}/>
                <LineChart data={data2} imageExport={['png, jpeg']}/>

            </div>
        );
    }
});


module.exports = App;

最佳答案

我是这样实现的:

index.html文件中,我使用带有初始状态属性的div,请参阅:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>React WebPack Barebones Example</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="css/app-custom.css">
    <link rel="stylesheet" href="css/daterangepicker-bs3.css" type="text/css" />
    <script src="build/main.bundle.js"></script>
</head>
<body>
 <nav class="navbar navbar-inverse navbar-fixed-top">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">React + CharJs</a>
        </div>
        <div id="navbar" class="navbar-collapse collapse">
          <form class="navbar-form navbar-right">
            <div class="form-group">
              <input type="text" placeholder="Email" class="form-control">
            </div>
            <div class="form-group">
              <input type="password" placeholder="Password" class="form-control">
            </div>
            <button type="submit" class="btn btn-success">Sign in</button>
          </form>
        </div><!--/.navbar-collapse -->
      </div>
    </nav>

    <div class="jumbotron">
      <div class="container">
        <h1>Hello React + ChartJs!</h1>
        <p>For more details, basic setup, usage, implementations see Github project</p>
        <p><a class="btn btn-primary btn-lg" href="https://github.com/rolandsusans/reactjs_chartjs" role="button">Get me to source &raquo;</a></p>
      </div>
    </div>

  <div class="container">
    <div class="ReactApp" type="LineChart" ajaxUrl="urlAjax1" excel="link1"pdf="link2"  minDate="02/02/2014" maxDate=""> </div>
    <div class="ReactApp" type="BarChart" excel="link3" pdf="link4" ajax="urlAjax2"></div> 
    <div class="ReactApp" type="BarChart" excel="link3" pdf="link4" ajax="urlAjax2"></div> 
  </div>

</body>

问题出在加载顺序上,React 之前已经加载过,所以我在 ma​​in.jsx 中实现了以下内容

    var React = require('react');
var App = require('./components/App');

function run() {
  // get all divs where Graphs should be rendered
  var targets = document.getElementsByClassName('ReactApp');

  for (var i = 0; i < targets.length; i++) {
     //actually call app render the graph with  
     React.render(<App />, targets[i]);
  };
}
if (window.addEventListener) {
  window.addEventListener('DOMContentLoaded', run);
} else {
  window.attachEvent('onload', run);
}

结果一切正常!应用程序按照我之前的意愿在多个 div 中呈现。

关于javascript - React 访问index.html 中的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30096483/

相关文章:

javascript - propTypes 声明中出现意外标记

javascript - 无法在 Gmail 中找到元素

javascript - 在Jquery中获取所选图像的值

javascript - 更新动态创建的组件

reactjs - Babel 6 对父级进行 super 构造函数调用会引发异常

reactjs - 生命周期方法和 useEffect 钩子(Hook)有什么区别?

javascript - 我想将我的数据附加到表格下方并在用户单击产品 ID 字段时进行搜索

php - 使用什么代替 if(isset($_POST ['submit' ])) for this.form.submit()?

javascript - 从其他文件访问变量

reactjs - Moment.js 与 ReactJS (ES6)