通过例子对比 AngularJS 和 React


似乎已经有无数比较这两个流行的JavaScript框架的文章,和往常一样,你能发现来自两个派别的意见。目前看来,大多数情况下,一个开发者的观点,会在他们工作中大多数使用哪个库/框架/SDK等方面,往往是相当激进的。你使用它来工作,你习惯了使用它,你喜欢上了它,然后你就会在互联网上言辞激烈地争论有关于它的信息。

因此会出现一种像“Angular和React哪个更好”这样的问题,这类似于询问两个中的哪个恰好更流行,但这并不总是最佳衡量指标。所以需要选择的新手开发者该怎么办呢?真实情况是一个产品比另一个产品流行不能证明它就是更好的,我们可以看到许多这种例子的产品。

在这篇文章中,我不会询问哪个更好,而是通过例子比较这两个著名的框架,并让读者选择它们更喜欢的那个。因为在每一种各自的“代码风格”里面存在一个显著的差别。

Demo - Data Grid

我想创建一个简单的data grid而且希望可以增加、移除和更新在网格里面的数据,并且能够以JSON对象的方式来发送网格里面全部的数据(供服务器处理)

如下图

使用Angular实现 —— 分而治之

Angular JS基于MVC设计模式。我们先用Javascript创建一个控制器:

var app = angular.module("myApp", []);
app.controller("ResourceController", function($scope) {
    $scope.resources = [{'ResourceAddress': 'http://www.discoversdk.com', 'ResourceDescription':'Great site'}];
    $scope.RemoveResource = function (index) {
        $scope.resources.splice(index, 1);
    }
        $scope.AddResource = function (newres) {
            if ($scope.resources == null) {
                $scope.resources = {};
                $scope.resources = [];
            }
            $scope.resources.push(
                {
                    ResourceAddress: newres.ResourceAddress,
                    ResourceDescription: newres.ResourceDescription,
                });
            newres.ResourceAddress = "";
            newres.ResourceDescription = "";
        }
        $scope.ShowRes = function () {
            alert(JSON.stringify($scope.resources));
        }
});

然后将标识的HTML文件与上面代码相关联:

<div ng-app="myApp" ng-controller="ResourceController">
    <fieldset >
            <h3>Add Resources</h3>
            <span >Description:</span>
            <input type="text" ng-model="newres.ResourceDescription" style="width:200px;" />
            <span > URL:</span>
            <input type="text" ng-model="newres.ResourceAddress" style="width:340px;"  />
            <a class="btn"  href="#" ng-click="AddResource(newres)">Add</a><br/>

            <h3>List of Resources</h3>
            <table   cellpadding="0" cellspacing="0">
                <tbody>
                <tr>
                    <th>Description</th>
                    <th>URL</th>
                    <th></th>
                </tr>
                <tr ng-repeat="res in resources">
                    <td><input style="width:200px;" type="text" ng-model="res.ResourceDescription" /></td>
                    <td><input style="width:440px;" type="text" ng-model="res.ResourceAddress" /></td>
                    <td><a class="btn"  ng-click="RemoveResource($index)">Remove</a></td>
                </tr>
                </tbody>
            </table>

             <a class="btn" href="#" ng-click="ShowRes()">Show</a>
    </fieldset>
</div>

然后用CSS文件添加样式:

body
{
  font-family:Arial;
  color:#3a3a3a;
}
table
{
  border:none;
  text-align:left;
  margin-bottom:20px;
}
tr th
{
    background-color: #3b97d3;
    color: #fff;
    padding: 5px;
    border-right: solid 1px #3b97d3;
    border-left: solid 1px #fff;
}
tr th:first-child
{
  border-left: solid 1px #3b97d3;
}
tr td
{
  padding:5px;
  padding: 5px;
  border-right: solid 1px #d4d4d4;
}
tr td:first-child
{
  border-left: solid 1px #d4d4d4;
}
table tr:last-child td
{
  border-bottom: solid 1px #d4d4d4;
}
input[type="text"]
{
  height:20px;
  font-size:14px;
}
a.btn
{
  color:#fff;
  background-color:#3b97d3;
  padding:0px 10px;
  height:26px;
  display:inline-block;
  line-height:26px;
  text-decoration:none;
  border-radius:3px;
  -moz-border-radius:3px;
  -webkit-border-radius:3px;
  cursor:pointer;
}
a.btn:hover
{
  background-color:#73c7ff;
}

你可以点击这里查看和运行代码

使用React实现——具有层次的GUI

我们通过React用层次结构组件构建用户界面,这主要的好处是代码复用

主要的区别是HTML,JavaScript,CSS代码混合到一起,但如果我们想在新的页面重用这个组件,我们只需要复制这一块的代码

所以在React里面,在我们的表格中我们这样在每一行构建一个List Item

var ResourceListItem = React.createClass({
    getInitialState: function() {
        return {ResourceDescription: this.props.children.ResourceDescription, ResourceAddress: this.props.children.ResourceAddress};
    },
    removeItem: function(e, index){
        this.props.removeItem(resources.indexOf(this.props.children));
    },
    updateDescription : function(e){
        resources[resources.indexOf(this.props.children)].ResourceDescription = e.target.value;
        this.setState({ResourceDescription: e.target.value});
    },
    updateAddress : function(e){
        resources[resources.indexOf(this.props.children)].ResourceAddress = e.target.value;
        this.setState({ResourceAddress: e.target.value});
    },
    render: function(){
        return (
            <tr>
            <td><input type="text" value={this.state.ResourceDescription} onChange={this.updateDescription} />{this.props.index}</td>
            <td><input type="text" value={this.state.ResourceAddress} onChange={this.updateAddress} /></td>
            <td><button onClick={this.removeItem.bind(null, this.props.children)}>remove</button></td>
            </tr>
        );
    } });

接着我们构建表格组件:

var RecourceList = React.createClass({
    render: function() {
        var that = this;
    var st = {
            backgroundColor: '#3b97d3',
            color: '#fff',
            padding: '5px',
            borderRight: 'solid 1px #3b97d3',
            borderLeft: 'solid 1px #fff'
        };
        var st2 = {
            padding: '5px',
            borderRight: 'solid 1px #d4d4d4',
            width: '250'
        };
        var createItem = function(itemText, index) {
            return (
                <ResourceListItem removeItem={that.props.removeItem} key={index}>{itemText}</ResourceListItem>
            );
        };

        return (
            <table>
                <thead>
                    <tr style={st}>
                        <td style={st2}>Description</td>
                        <td style={st2}>Url</td>
                        <td></td>
                    </tr>
                </thead>
                <tbody>
                    {this.props.items.map(createItem)}
                </tbody>
            </table>
        )
    } });

然后我们用同样的方式添加网格组件并声明我们的应用:

var MainApp = React.createClass({
    getInitialState: function() {
        return {items : resources};
    },
    addItems: function(newItem){
        resources = resources.concat([newItem]);
        this.setState({items: resources});
    },
    removeItem: function(itemIndex){
        resources.splice(itemIndex, 1);
        this.setState({items: resources});
    },
    show: function(){
        alert(JSON.stringify(resources));
    },
    render: function(){
        return (
            <fieldset>
            <div>
                <h3>Add Resources</h3>
                <AddResourceForm onFormSubmit={this.addItems} />
                <a href="#" onClick={this.show}>Show</a>
                <h3>List of Resources</h3>
                <RecourceList items={this.state.items} removeItem={this.removeItem} />
            </div>
            </fieldset>
        );
    } });

你可以点击这里查看并运行代码(要注意的是jsfiddle的react支持有一点限制因此它会更改代码,你需要选择常规的JavaScript并选择回退JavaScript7来运行它)

文章转载自 开源中国社区[http://www.oschina.net]

时间: 2024-07-28 18:17:47

通过例子对比 AngularJS 和 React的相关文章

Java和C#运行命令行的例子对比

呵呵,刚给客户解决了在C#里运行命令行的例子,顺便整理了一下Java的例子,大家参考对比一下 Java的 import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; /** * Java运行命令行的例子 * * @author JAVA世纪网(java2000.net) */ public class TestProcess { public static void ma

PHP传值与传引用的区别例子对比

传值:是把实参的值赋值给行参 ,那么对行参的修改,不会影响实参的值 传引用 :真正的以地址的方式传递参数传递以后,行参和实参都是同一个对象,只是他们名字不同而已对行参的修改将影响实参的值    代码如下 复制代码 $b=1; //定义变量2 $1= &$b; //将变量2的引用传给变量1 echo $b.'<br />'; //显示为1 echo $a; $a= 2; //把2赋值给变量1 echo $b; //显示为2 一,php实例 1,传值 . 代码如下:  代码如下 复制代码

在React框架中实现一些AngularJS中ng指令的例子_AngularJS

首先设定一段Angularjs代码的ng-class: <i class="header-help-icon down" ng-class="{up:showMenu}"></i>   比较容易理解的Angularjs ng-class设置样式代码,那我们使用React怎么去实现它呢? 首先在state设置一个变量比如: isShowLoginMenu,在不同场景改变它的值,然后在绑定在class样式上面      <i classNa

AngularJS一个简单的时钟展示实现例子

一个简单的时间显示 <html> <head>  <link href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">     <script src="//cdn.bootcss.com/angular.js/1.3.17/angular.js"></script>     <

使用react来增强backbone视图功能

曾经用backbone做了几个项目,对它里面的视图功能真是不敢恭维,基本上用它作为前端mvc框架的都是为了兼容性,不过随着M$对xp的放弃,以及win7未来的不支持,IE8已经成了不少公司兼容IE的底限了,所以这时候假如还用Backbone的话,确实有点对不起住自己,不过有些时候不是你想用什么就用什么的,所以这时候你就要想办法去提高backbone视图功能,这时候该是react出马的时候了, React概览 react首先它是一个ui框架,用来创建独立的前端UI组件用的,类似于angularjs

利用browserify和gulp来构建react应用

JS的世界发展的非常快,有很多好用的框架,工具层出不穷,今天就来说说怎么结合browserify,gulp,react来构建前端应用. 下面我们先一一简单介绍下browserify,gulp,react Browserify browserify是一个以commonjs规范来定义模块的打包工具. browserify是一个开发工具,它允许我们以nodejs的代码风格来定义我们的模块,使用module.exports来导出模块功能,使用require来请求某个模块,跟amd规范不一样的是,我们不需

一篇包含了React所有基本点的文章

去年,我写了一本关于学习React.js的小书,原来是大约100页. 今年我要挑战自己,把它归纳为一篇文章. 本文不会涵盖什么是React,或者为什么要学习它. 相反,这是面向已经熟悉JavaScript并熟悉DOM API基础知识的人,对React.js的基础知识的介绍. 以下所有代码示例均标示为参考. 它们纯粹是为了提供概念而写的例子. 他们大多数可以写得更好一些. 1:组件是React的一切 React是围绕可重用组件的概念设计的. 您定义小组件,并将它们放在一起形成更大的组件. 所有小或

React Native Android 应用内存使用探究

本文讲的是React Native Android 应用内存使用探究, 为什么我那台老旧的 Android 手机无法加载图片? 刚开始接触 React Native 应用时,我发现有个现象很奇怪,在 Android 手机上我无法看到任何图片,只有颜色和文字可以显示.但 iOS 手机却没有任何问题. 我以为是我新找来测试 React Native 工程的 Android 手机有问题.我甚至被这错误的想法牵着刷了 rom (基于 AOSP 5.1.1 的系统)来在更高的 Android 版本上运行

webstorm+react+webpack-demo

准备:安装好webstorm和nodejs 一.开始: 1.新建一个demo04文件夹为项目根目录,下面2个子文件夹分别是src和public a:public目录下一个index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>webstorm+react+webpack</title> &l