谁能解释一下 Reacts 单向数据绑定和 Angular 的双向数据绑定的区别 [英] Can anyone explain the difference between Reacts one-way data binding and Angular's two-way data binding

查看:18
本文介绍了谁能解释一下 Reacts 单向数据绑定和 Angular 的双向数据绑定的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对这些概念有点模糊,如果我完全在 AngularJS 和 ReactJS 中构建相同的 ToDo 应用程序——是什么让 React ToDo 使用单向数据绑定与 AngularJS 的双向数据绑定?

I'm a bit fuzzy on these concepts, If I build the same ToDo app completely in AngularJS and ReactJS--- what makes the React ToDo use one-way data binding vs the AngularJS's two-way data binding?

我知道 React 有点像

I understand that React sort of works like

渲染(数据)---> UI.

Render(data) ---> UI.

这与 Angular 有何不同?

How is this different from Angular?

推荐答案

Angular

当 angular 设置数据绑定两个观察者"时存在(这是一个简化)

Angular

When angular sets up databinding two "watchers" exist (this is a simplification)

//js
$scope.name = 'test';
$timeout(function()  { $scope.name = 'another' }, 1000);
$timeout(function()  { console.log($scope.name); }, 5000);

<!-- html --->
<input ng-model="name" />

输入将从 test 开始,然后在 1000 毫秒内更新到 another.对 $scope.name 的任何更改,无论是来自控制器代码还是更改输入,都将在 4000 毫秒后反映在控制台日志中.对 的更改会自动反映在 $scope.name 属性中,因为 ng-model 设置监视输入并通知 $scope 更改.代码更改和 HTML 更改是双向绑定.(查看这个小提琴)

The input will start out with test, then update to another in 1000ms. Any changes to $scope.name, either from controller code or by changing the input, will be reflected in the console log 4000ms later. Changes to the <input /> are reflected in the $scope.name property automatically, since ng-model sets up watches the input and notifies $scope of the changes. Changes from the code and changes from the HTML are two-way binding. (Check out this fiddle)

React 没有允许 HTML 更改组件的机制.HTML 只能引发组件响应的事件.典型的例子是使用 onChange.

React doesn't have a mechanism to allow the HTML to change the component. The HTML can only raise events that the component responds to. The typical example is by using onChange.

//js
render() { 
    return <input value={this.state.value} onChange={this.handleChange} />
}
handleChange(e) {
    this.setState({value: e.target.value});
}

的值完全render 函数控制.更新此值的唯一方法是从组件本身,这是通过将 onChange 事件附加到设置 this 的 来完成的.state.value 使用 React 组件方法 setState. 不能直接访问组件状态,因此无法进行更改.这是单向绑定.(查看此 codepen)

The value of the <input /> is controlled entirely by the render function. The only way to update this value is from the component itself, which is done by attaching an onChange event to the <input /> which sets this.state.value to with the React component method setState. The <input /> does not have direct access to the components state, and so it cannot make changes. This is one-way binding. (Check out this codepen)

这篇关于谁能解释一下 Reacts 单向数据绑定和 Angular 的双向数据绑定的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆