必备知识
Requirejs、Angularjs、Reactjs,可查看本博客写的相关内容进行必备知识了解。
整合Angular.js、React.js
本人在angular.js之爱恨情仇中已提到过Angular.js的性能问题,而React.js基于virtual dom的方式渲染页面,在性能上有不错的表现,所以在系统中整合了React.js。
Requirejs配置
requirejs.config({
baseUrl: ‘/‘,
paths: {
‘jquery‘: ‘libs/jquery-2.1.3/jquery.min‘,
‘angular‘: ‘libs/angular-1.3.15/angular.min‘,
‘React‘: ‘libs/react-0.13.3/react.min‘,
// 使用JSX方式编写React,其依赖以下三个文件
// React JSX
‘JSXTransformer‘: ‘libs/react-0.13.3/JSXTransformer‘,
// require jsx
‘jsx‘: ‘libs/react-0.13.3/jsx‘,
// require text
‘text‘: ‘libs/react-0.13.3/text‘
},
shim: {
‘angular‘: {
deps: [‘jquery‘],
exports: ‘angular‘
},
‘React‘: {
exports: ‘React‘
}
},
waitSeconds: 0
});
计时器组件Timer
使用Reactjs编写计时器组件Timer。
注意: JSX文件所在目录不要取名为jsx,否则会导致解析失败。
Timer.js
// 依赖名称必须为React(首字母),否则JSX解析后无法找到React
define([‘React‘], function(React) {
var TimeMessage = React.createClass({
render: function() {
var elapsed = Math.round(this.props.elapsed / 100);
var seconds = elapsed / 10 + (elapsed % 10 ? ‘‘ : ‘.0‘ );
// 在此处JSX将解析为return React.createElement("p", null, "React has been successfully running for ", seconds, " seconds.");
// 所以依赖名称要为React,否则React -> undefined
return <p>React has been successfully running for {seconds} seconds.</p>;
}
});
var Timer = React.createClass({
getInitialState: function() {
return {now: new Date()};
},
componentDidMount: function() {
var that = this;
setInterval(function() {
that.setState({now: new Date()});
}, 50);
},
render: function() {
var elapsed = this.state.now.getTime() - this.props.start.getTime();
return <TimeMessage elapsed={elapsed} />;
}
});
return Timer;
});
Angular.js使用React组件
define([
‘angularApp‘, ‘React‘,
‘jsx!jsxdir/Timer‘ // 使用jsx!XXXX形式引入
], function (
angularApp, React,
Timer
) {
// 在angular controller中使用React组件,同理在Directive的link中使用
angularApp.controller(‘welcomeCtrl‘, [‘$scope‘, function($scope) {
var start = new Date();
Timer = React.createFactory(Timer);
React.render(
Timer({start: start}),
// 页面中div元素
document.getElementById(‘testJSX‘)
);
}]);
});
页面效果
时间: 2024-12-25 23:46:48