任何人都可以解释Reacts单向数据绑定和Angular的双向数据绑定之间的区别 [英] Can anyone explain the difference between Reacts one-way data binding and Angular's two-way data binding
问题描述
我对这些概念有点模糊,如果我在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
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毫秒内更新到另一个
。对控制器代码或更改输入的 $ scope.name
的任何更改都将在4000ms后的控制台日志中反映出来。对< input />
的更改自动反映在 $ 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});
}
< input />的值
由 render
函数完全控制 。更新此值的唯一方法是从组件本身,通过将 onChange
事件附加到< input />
使用React组件方法 setState
将 this.state.value
设置为。 < input />
无法直接访问组件状态,因此无法进行更改。这是单向绑定。 (查看此 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屋!