react2angular 替换可行性研究
【摘要】 这个程序库从功能上讲,是在Angular 1的项目中使用react的代码。
1 安装
# 使用Yarn
yarn add react2angular react react-dom prop-types
# 或者使用NPM:
npm install react2angular react react-dom prop-types --save
2 用法
1. 创建一个React组件
import { Component } from 'react'
class MyComponent extends Component {
render() {
return <div>
<p>FooBar: {this.props.fooBar}</p>
<p>Baz: {this.props.baz}</p>
</div>
}
}
2. 将其暴露给Angular1
import { react2angular } from 'react2angular'
angular
.module('myModule', [])
.component('myComponent', react2angular(MyComponent, ['fooBar', 'baz']))
注意:如果你在组件上定义了propTypes,它们将被用来计算组件的绑定,你可以省略第二个参数。
...
.component('myComponent', react2angular(MyComponent))
如果定义了propTypes,并且你传入了第二个参数,那么这个参数将覆盖propTypes。
3. 在你的Angular 1代码中使用它
<my-component
foo-bar="3"
baz="'baz'"
></my-component>
注意:所有的React属性都会转换为AngularJS的单向绑定。如果你要将函数传递到你的React组件中,需要将其作为函数ref传递,而不是作为可调用的表达式。保留现有的 AngularJS 风格的表达式会导致无限循环,因为函数会在每个摘要循环上重新评估。
3 依赖性注入
很容易将服务/常量/等传递到你的React组件中:只需将它们作为第3个参数传递进来,它们就会在你的组件的Props中可用。比如说
import { Component } from 'react'
import { react2angular } from 'react2angular'
class MyComponent extends Component {
state = {
data: ''
}
componentDidMount() {
this.props.$http.get('/path').then(res =>
this.setState({ data: res.data })
)
}
render() {
return <div>
{ this.props.FOO }
{ this.state.data }
</div>
}
}
angular
.module('myModule', [])
.constant('FOO', 'FOO!')
.component('myComponent', react2angular(MyComponent, [], ['$http', 'FOO']))
注意:如果你有一个与属性名称相匹配的注入,那么该值将与注入一起解析,而不是属性。
4 对此类程序库的分析
这个程序库从功能上讲,是在Angular 1的项目中使用react的代码。
就目前的情况来看,Angular 1已经被Angular所取代。那么处理Angular 1项目的重构问题的最好办法是用Angular技术。
这种在Angular 1的项目中使用react技术的方法非常不可取,这会人为的增加整个项目的复杂度,增加维护的成本。
所以目前我的建议是不需要寻找这个程序库的替代品。
正确的做法是逐步的把现有的Angular 1代码转化成Angular。
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
作者其他文章
评论(0)