如何在单独的文件中正确存储React组件并导入React? [英] How to properly store React components in separate files and import React?

查看:99
本文介绍了如何在单独的文件中正确存储React组件并导入React?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经完成了一些React教程的介绍,并试图将我的一些知识用于目前。我已成功在< script type ='text / babel'> 中创建了一些组件,并使用了babel的 browser.js 在浏览器中将其转换为JS客户端。

I've completed a few intro to React tutorials and am trying to put some of my knowledge so far to use. I've successfully created some components inside of a <script type='text/babel'> and using babel's browser.js to convert this to JS client-side in the browser.

然而,我现在正试图将我的组件分解为单个文件,转换它们,然后将已转换的JS提供给客户端,而不是将其转换为客户端-侧。

However, I'm now trying to break out my components into individual files, transpile them, and then serve the transpiled JS to the client rather than have that transpilation done client-side.

我对如何将ReactJS正确导入我的组件JSX文件感到困惑。我之前没有构建过大型JS应用程序,因此我不熟悉将库导入其他模块的方法。

I'm confused on how to properly import ReactJS into my component JSX files. I haven't built large JS applications before, so I'm not familiar with the ways to import libraries into other modules.

这是我的一个组件JSX文件:

Here's one of my component JSX files:

var SidebarFilter = React.createClass({
  render: function() {
    return (
        <div className="btn-group">
          Some markup removed for brevity. 
        </div>
    );
  }
});

在我的主html文件中,如果我有:

In my main html file, if I have:

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-dom.js"></script>

在我的任何< script> 我的组件的标签,一切正常。但是,如果组件放在react / reactdom脚本标记之上,则它不起作用。

Prior to any of my <script> tags for my components, everything works fine. But if the components are placed above the react/reactdom script tags, it doesn't work.

我见过javascript有一个 import ,还有 require ,但我不确定区别是什么,哪个更好,何时使用,以及是否需要任何额外的构建或者如果它们在浏览器中使用的话。

I've seen javascript has an import and there is also require, but I'm not sure what the differences are, which is better to use when, and if either/both require any additional building or if they're used right in the browser.

谢谢!

推荐答案

如果你刚学习反应那么你的使用脚本标签的方式是在html内部。

If you are just learning react then your way of doing using script tag is inside html fine.

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-dom.js"></script>

如果要开发可部署到生产的应用程序,则需要按照以下步骤操作。毫无疑问,互联网上有更好的教程,但它会给你一些想法。

If you want to develop an application which can be deployed to production you need to follow following steps. No doubt there are much better tutorial available over the internet but it will give you some idea.

1.Need Browserfiy或Webpack:

在浏览器中,您不能需要导入模块通常在编写node.js代码时执行。在 Browserify / Webpack 的帮助下,您可以编写使用 require / import 的代码,方法与在节点环境中使用它的方式相同。我假设您将使用 webpack 考虑其受欢迎程度。

In browsers you can not require or import modules as you usually do while writing node.js code. With the help of Browserify/Webpack you can write code that uses require/import in the same way that you would use it in node environment. I am assuming you will use webpack considering its popularity.

2。安装依赖项(es6)

这些是项目中需要的最小依赖项( package.json )让它运作

These are minimal dependencies you need in your project (package.json) to get it working

  "devDependencies": {
        "babel-cli": "^6.3.17",
        "babel-core": "^6.3.21",
        "babel-eslint": "^5.0.0-beta6",
        "babel-loader": "^6.2.0",
        "babel-preset-es2015": "^6.3.13",
        "babel-preset-react": "^6.3.13",
        "babel-preset-stage-3": "^6.3.13",
        "css-loader": "^0.23.0",
        "eslint": "^1.10.3",
        "eslint-loader": "^1.1.1",
        "eslint-plugin-react": "^3.12.0",
        "style-loader": "^0.13.0",
        "webpack": "^1.12.9",
        "webpack-dev-server": "^1.14.0"
      },
      "dependencies": {
        "react": "^15.0.0-rc.1",
    "react-dom": "^15.0.0-rc.1"

3.写你的webpack-config.js文件

示例 webpack 配置文件应该是这样的。不要问我关于它的每一点,而是看看 webpack 教程,因为我无法解释这里的一切。请记住,
Webpack 是一个模块捆绑包,它捆绑了 javascript 和浏览器的其他资产。

A sample webpack config file should like this. Don't ask me about each bit of it but rather have a look on webpack tutorial because I can not explain everything here. Just remember the fact that Webpack is a module bundler that bundles javascript and other assets for the browser.

var path    = require('path');
var webpack = require('webpack');

module.exports = {
  devtool: 'source-map',
  entry: {
    main: [
      'webpack-dev-server/client?http://localhost:8080',
      'webpack/hot/only-dev-server',
      './src/index.js'
    ]
  },
  output: {
    path: path.join(__dirname, 'public'),
    publicPath: 'http://localhost:8080/public/',
    filename: 'bundle.js'
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ],
  module: {
   loaders: [
      {
        test      : /\.jsx?$/,
        include   : path.join(__dirname, 'src'),
        loader    : 'react-hot!babel'
      },
      {
        test      : /\.scss$/,
        include   : path.join(__dirname, 'sass'),
        loaders   : ["style", "css?sourceMap", "sass?sourceMap"]
      },
      {
          test    : /\.(png|jpg|svg)$/,
          include : path.join(__dirname, 'img'),
          loader  : 'url-loader?limit=30000&name=images/[name].[ext]'
     } // inline base64 URLs for <=30k images, direct URLs for the rest
    ]
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  devServer: {
    historyApiFallback: true,
    contentBase: './'
  }
};

4.设置应用程序的入口点和路线

src-> index.js
src-> routes.js

src->index.js src->routes.js

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import {Router,browserHistory} from 'react-router';
import routes from './routes';

ReactDOM.render(
    <Router routes={routes} history={browserHistory}/>
  , document.querySelector('.init')
);

routes.js

routes.js

import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './components/app';
import Home from './components/home';


module.exports = (
       <Route path="/" component={App}>
           <IndexRoute component={Home}/>
       </Route>
)

5.Setup项目根目录中的index.html

<!DOCTYPE html>
<html>
  <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Welcome to ReactJs</title>
  </head>
  <body>
    <div class="init"></div>
  </body>
  <script src="./public/bundle.js"></script>
</html>

6.运行

形成项目根类型

webpack-dev-server --progress --colors

导入和需要

import require 在功能上非常相似。唯一的区别是 import 是es6可用的新语法糖,而 require 与es5一起使用。

import and require are very similar in functionality. Only difference is that import is new syntactic sugar available with es6 while require is used with es5.

这篇关于如何在单独的文件中正确存储React组件并导入React?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆