将React类移动到单独的文件中 [英] Moving React classes into separate files
问题描述
执行 React教程后,这是我的index.html文件:
After doing the React tutorial this is my index.html file:
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.2/marked.min.js"></script>
</head>
<body>
<div id="content"></div>
<script src="lib/main.js"></script>
</body>
</html>
这是我的src / main.jsx文件:
And this is my src/main.jsx file:
var CommentBox = React.createClass({
getInitialState: function() {
return {data: []};
},
loadCommentsFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
handleCommentSubmit: function(comment) {
var comments = this.state.data;
var newComments = comments.concat([comment]);
this.setState({data: newComments});
$.ajax({
url: this.props.url,
dataType: 'json',
type: 'POST',
data: comment,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
componentDidMount: function() {
this.loadCommentsFromServer();
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
},
render: function() {
return (
<div className="commentBox">
<h1>Comments Yo</h1>
<CommentForm onCommentSubmit={this.handleCommentSubmit} />
<CommentList data={this.state.data} />
</div>
);
}
});
var CommentForm = React.createClass({
handleSubmit: function(e) {
e.preventDefault();
var author = React.findDOMNode(this.refs.author).value.trim();
var text = React.findDOMNode(this.refs.text).value.trim();
if (!text || !author) {
return;
}
// send request to the server
this.props.onCommentSubmit({author: author, text: text});
React.findDOMNode(this.refs.author).value = '';
React.findDOMNode(this.refs.text).value = '';
return;
},
render: function() {
return (
<form className="commentForm" onSubmit={this.handleSubmit}>
<input type="text" placeholder="Your name" ref="author" />
<input type="text" placeholder="Say something..." ref="text" />
<input type="submit" value="Post" />
</form>
);
}
});
var CommentList = React.createClass({
render: function() {
var commentNodes = this.props.data.map(function (comment) {
return (
<Comment author={comment.author}>
{comment.text}
</Comment>
);
});
commentNodes.reverse();
return (
<div className="commentList">
{commentNodes}
</div>
);
}
});
var Comment = React.createClass({
render: function() {
var rawMarkup = marked(this.props.children.toString(), {sanitize: true});
return (
<div className="comment">
<h2 className="commentAuthor">
{this.props.author}
</h2>
<span dangerouslySetInnerHTML={{__html: rawMarkup}} />
<hr />
</div>
);
}
});
React.render(
<CommentBox url="comments.json" pollInterval={2000} />,
document.getElementById('content')
);
此外,我正在运行此命令将我的jsx变成js:
Additionally, I am running this command to turn my jsx into js:
babel --watch src/ --out-dir lib/
我想将每个React类移动到自己的文件中。例如,我想创建以下四个文件(注意:每个映射到我的main.jsx文件中的顶级var声明)并将所有这些类拉入我的main.jsx文件中:
I would like to move each React class into its own file. For example, I would like to create the following four files (note: each map to a top level "var" declaration in my main.jsx file) and pull all of these classes into my main.jsx file:
comment.jsx
commentList.jsx
commentForm.jsx
commentBox.jsx
我该怎么办?
在敲响了需求之后es6在这里呆了一段时间,我仍然没有很好的直觉知道如何将所有这些分开,或者如果需要/ es6这样的东西甚至是接近它的正确方法。
After banging my head on require and es6 for a while here, I still do not have a good intuition of how to separate all these apart, or if something like require / es6 is even the right way to approach this.
感谢您的帮助!
推荐答案
如果您想为每个React类创建一个文件,我建议您看一下 webpack 。你可以将你的React类开发为CommonJs模块,它会将它们捆绑在一起。
If you want to create a file for each React class, I would recommend to take a look at webpack. You can develop your React classes as CommonJs modules and it will take care of bundling them together.
另外,我认为这是一个很好的选择,因为你想使用 babel 转换您的 jsx 文件。这可以通过 webpack加载器解决。
Also, I think it is a good option because you want to use babel to transform your jsx files. This is solved with webpack loaders.
基本的webpack配置文件包含如下内容:
The basic webpack configuration file would contain something like this:
webpack.config.js
var webpack = require('webpack');
module.exports = {
entry: './src/main.jsx',
output: {
// Output the bundled file.
path: './lib',
// Use the name specified in the entry key as name for the bundle file.
filename: 'main.js'
},
module: {
loaders: [
{
// Test for js or jsx files.
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel'
}
]
},
externals: {
// Don't bundle the 'react' npm package with the component.
'react': 'React'
},
resolve: {
// Include empty string '' to resolve files by their explicit extension
// (e.g. require('./somefile.ext')).
// Include '.js', '.jsx' to resolve files by these implicit extensions
// (e.g. require('underscore')).
extensions: ['', '.js', '.jsx']
}
};
我创建了一个GitHub react-tutorial-webpack 存储库。
I created a GitHub react-tutorial-webpack repository if you want to have actual code.
这篇关于将React类移动到单独的文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!