【问题标题】:How to use ReactJS components defined in one .js file in a html file如何在 html 文件中使用一个 .js 文件中定义的 ReactJS 组件
【发布时间】:2016-12-01 13:54:14
【问题描述】:

我在我的 HTML 文件中定义了我的 reactjs 组件,如下所示:

<script type="text/babel">
 var WorkHistory = React.createClass({
......
});
                  ReactDOM.render(
                        <WorkHistory 
                        />,
                        document.getElementById('work_history')
                    );
</script>

现在,我可以轻松地在我的 HTML 页面中使用它。但是,我需要像这样编写整个代码:

WORKHISTORY.js 文件:

var WorkHistory = React.createClass({
    ......
    });

WORKHISTORY.html 文件:

<script type="text/babel">
                      ReactDOM.render(
                            <WorkHistory 
                            />,
                            document.getElementById('work_history')
                        );
</script>

我怎样才能做到这一点??

【问题讨论】:

    标签: javascript html reactjs react-jsx reactjs-native


    【解决方案1】:

    如果我正确理解了您的问题,您希望将组件写入单独的 .js-files 并能够在您使用 ReactDOM.render&lt;script&gt;-tag 中访问它们吗?

    如果是这种情况,只需将&lt;script&gt;-tags 与src-attribute 设置为您的文件路径在呈现标签之前,按照我的示例:

    <script src="./path/to/workhistory.js"></script>
    <script type="text/babel">
      ReactDOM.render(
        <WorkHistory />,
        document.getElementById('work_history')
      );
    </script>
    

    【讨论】:

    • 在这种情况下我得到一个错误:'ReferenceError: WorkHistory is not defined'
    • 哦,我现在看到您正在使用 Babel 转译您的代码。 Babel 将转换您的代码并预先添加 'use strict',它封装了该文件的范围,防止您的其他 script-tags 访问其变量。如果您只是测试内容,则可以在分配和访问变量时使用全局范围 - window,但更好的解决方案是将 a build system 与 Babel 一起使用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-24
    • 2020-02-12
    • 1970-01-01
    • 2020-02-05
    • 2019-05-23
    相关资源
    最近更新 更多