Can anyone explain the difference between Reacts one-way data binding and Angular's two-way data binding

前端 未结 3 1544
无人及你
无人及你 2020-12-07 07:23

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\'

3条回答
  •  轮回少年
    2020-12-07 08:04

    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);
    
    
    
    

    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 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

    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 
    }
    handleChange(e) {
        this.setState({value: e.target.value});
    }
    

    The value of the 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 which sets this.state.value to with the React component method setState. The does not have direct access to the components state, and so it cannot make changes. This is one-way binding. (Check out this codepen)

提交回复
热议问题