简体   繁体   English

将React组件拆分为单独的文件

[英]Splitting React components into separate files

This seems to be a common question, I'm finding a lot of people asking it and the responses are all very different and seem to be a bit hit and miss. 这似乎是一个常见的问题,我发现很多人都在问它,而且反应都非常不同,似乎有点受到打击。 I've watched various video tutorials, read plenty of tutorials, and the documentation. 我看了各种视频教程,阅读了大量的教程和文档。 But alas it seems React is moving faster than the writers can keep up with. 但唉,似乎React的速度超过了作家可以跟上的速度。 Or I'm just misunderstanding. 或者我只是误会。

I want to create each component in a separate file, where logical to do so. 我想在一个单独的文件中创建每个组件,逻辑上这样做。 I have React working, but am unable to work out how to import and use additional files. 我有React工作,但我无法弄清楚如何导入和使用其他文件。 I don't know if this is because Chrome will not load in files when not on a web server (local test dev), or if I'm just going about it all wrong. 我不知道这是不是因为当不在Web服务器(本地测试开发)上时Chrome不会加载文件,或者我只是错误地加载它。

Here is my HTML: 这是我的HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>React Test One</title>
</head>
<body>
<div id="rootNode"></div>
<script src="dist/bundle.js"></script>
</body>
</html>

And here is my main.js: 这是我的main.js:

var React = require('react');
var ReactDOM = require('react-dom');
var Square = require('../components/square.jsx').square;

ReactDOM.render(
    <div>
        <h1>Hello React!</h1>
        <Square />
    </div>,
    document.getElementById('rootNode')

);

This works fine if I don't try to use Square also. 如果我不尝试使用Square也可以。

This is my square.jsx: 这是我的square.jsx:

class Square extends React.Component{
    render() {
        return (
            <p>Square</p>
        )
    }
}

module.exports = {
    square: Square
};

Babel create the bundle.js fine, no errors. Babel创建bundle.js很好,没有错误。 Chrome throws the error: Chrome会抛出错误:

Uncaught SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode 未捕获的SyntaxError:在严格模式之外尚不支持块范围的声明(let,const,function,class)

I have tried the following also for square, along with many other things, all lost from the undo queue: 我已经尝试了以下方法,以及许多其他东西,所有这些都从撤消队列中丢失:

import React from 'react';

class Square extends React.Component{
    render() {
        return (
            <p>Square</p>
        )
    }
}

export default Square;

All help appreciated. 所有帮助赞赏。 React seems to make sense aside from separating out the class files. 除了分离类文件之外,React似乎有意义。

Thanks. 谢谢。

EDIT: 编辑:

Also tried: 还尝试过:

var {Component} = React;

class Square extends Component{
    render() {
        return (
            <p>Square</p>
        )
    }
}

window.Square = Square;

And if it helps here is the Gulp file: 如果它有帮助,这里是Gulp文件:

var vendors = [
    'react'
];

gulp.task('vendors', function () {
    var stream = browserify({
        debug: false,
        require: vendors
    });

    stream.bundle()
        .pipe(source('./src/main.js'))
        .pipe(gulp.dest('./dist/bundle.js'));

    return stream;
});

And the package.json: 而package.json:

{
  "name": "reacttestone",
  "version": "1.0.0",
  "description": "Testing React Components",
  "main": "index.js",
  "dependencies": {
    "babel-preset-react": "^6.1.2",
    "babelify": "^7.2.0",
    "react": "^0.14.2",
    "react-dom": "^0.14.2"
  },
  "devDependencies": {
    "gulp": "^3.9.0",
    "vinyl-source-stream": "^1.1.0"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Myself",
  "license": "MIT"
}

Your es6 example of exporting like export default Square should work fine. 您的es6导出示例如export default Square应该可以正常工作。 It looks like you've installed babelify but you're not using it in the transform process, hence why the browser is complaining that you're trying to use es6 features outside of strict mode. 看起来你已经安装了babelify,但是你没有在转换过程中使用它,因此浏览器抱怨你试图在严格模式之外使用es6功能。

If you look at the babelify instructions it says to do something like: 如果你看一下babelify说明,它会说:

var gulp = require('gulp');
var browserify = require('browserify');
var babelify = require('babelify');
var source = require('vinyl-source-stream');
var gutil = require('gulp-util');

gulp.task('browserify', function () {
    browserify('./src/main.js', { debug: true })
        .transform('babelify', {presets: ['es2015', 'react']})
        .bundle()
        .on('error', gutil.log)
        .pipe(source('bundle.js'))
        .pipe(gulp.dest('./dist'))
});

gulp.task('watch',function() {
    gulp.watch('./src/**/*.js', ['browserify'])
});

It looks like you only have babel-preset-react installed, you'll need to do npm i babel-preset-es2015 --save-dev . 看起来你只安装了babel-preset-react ,你需要做npm i babel-preset-es2015 --save-dev Also babelify and babel-preset-react are fine as devDependencies . babelifybabel-preset-react也可以作为devDependencies

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM