簡體   English   中英

將React組件拆分為多個文件

[英]Splitting up React components into multiple files

我只在一周內學習了React,所以我是新手,我正在嘗試編寫一個簡單的待辦事項應用程序。

最初我在一個文件中編寫了所有組件,並將該文件加載到HTML文件中,效果很好。 現在我正在重構並嘗試將組件拆分為不同的文件。

我的完整代碼在extract extracting-files分支上的我的Github https://github.com/yasgreen93/todolist-react上。

我已將每個組件拆分為不同的文件,並將腳本標記中的鏈接鏈接到我的HTML中。 這是我的HTML文件的樣子:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Todo List</title>
    <link rel="stylesheet" href="css/styles.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react-dom.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.6.16/browser.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
  </head>

  <body>
    <div id="container"></div>
    <script type="text/babel" src="scripts/components/TodoListApp.js"> </script>
    <script type="text/babel" src="scripts/components/CompleteTodo.js"></script>
    <script type="text/babel" src="scripts/components/TodoList.js"></script>
    <script type="text/babel" src="scripts/components/SingleTodo.js"></script>
    <script type="text/babel" src="scripts/components/AddTodo.js"></script>
    <script type="text/babel" src="scripts/components/CompleteTodoButton.js"></script>

    <script type="text/babel">
      ReactDOM.render(
        <TodoListApp url="/api/todos" updateUrl="/api/todos/update" pollInterval={2000}/>,
        document.getElementById('container')
      );
    </script>
  </body>
</html>

在控制台中,我總是收到錯誤消息Uncaught ReferenceError: TodoListApp is not defined 我試過以不同的順序加載它們但沒有成功。 我還觀看了許多視頻,他們在不使用webpack的情況下做了非常相似的方法,它適用於他們。 我想首先使用webpack,然后繼續學習。

任何人都可以看到我錯在哪里?

您必須將組件添加到全局window變量,以便在html script標記中使用它們。 window.TodoListApp =... var聲明是相對於您聲明它的文件。

但是,將部分代碼暴露給全局范圍並在瀏覽器中轉換JSX被認為是一種不好的做法。 相反,你應該考慮使用像Webpack這樣的建築系統。

通過這種方式,您可以使用es2015導入語法將組件從一個文件導入到另一個文件,將所有內容捆綁到一個文件中,以及更多其他好處,如代碼縮小,源映射,實時重載等。

使用Webpack和Babel為ES6設置React

在Webpack教程中使用React

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM