简体   繁体   中英

data binding in react.js

I want to bind my global variable testdata to the react UI.
I did find the following solution:

var testdata = 'initial value';

function change() {
    testdata = 'changed value';
}

var Test = React.createClass({
    displayName: 'Test',
    render: function () {
        return React.DOM.div(null,
          React.DOM.div(null, this.props.data )
        );
    }
});

setInterval(function () {
    React.renderComponent(
      Test({ data: testdata }),
      document.getElementById('test')
    );
}, 1000);

My question: is there more elegant way (without setInterval) of doing it?

Allow me to rephrase your question:

How do I rerender react when external data changes?

In order to do this, you need to be able to run some code when the external data changes. If you can't do this, then you can't update the view. There's no magic.

get/set

One way is with a getter and setter.

renderOnChange({
    key: 'testdata',
    element: document.getElementById('test'),
    render: function(data){ return Test({data: data.testdata}); }
});
function renderOnChange(params){
   var source = params.source || window, key = params.key, element = params.element, render: params.render;
   var value = source[key];
   delete source[key];
   Object.defineProperty(source, key, {
       get: function(){ return value },
       set: function(newValue){ 
           value = newValue;
           React.renderComponent(render(source), element);
       }
   });
}

I might add more methods here later on

You can re-render inside your change method(s).

function render() {
    var component = Test({ data: testdata });
    var root = document.getElementById('test');
    React.renderComponent(component, root);
}

function change() {
    testdata = 'changed value';
    render();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM